-2

I have been searching for hours and my solution seems right, but it's not working.

The data returned from the server is a partial view, so it contains nothing but html and a script or two.

I've tried searching the children of the data but I always get a count of 0. Here is my script:

<script type="text/javascript">
    function submit_onClick()
    {
        $.ajax({
            method: "POST",
            url: "/Projects/CreateProject",
            cache: false
        }).success(function (data) {
            if ($(data).children('span[class="field-validation-error"]').length == 0) {
                window.location.assign("/Projects/Index");
                alert("New Project request submitted successfully.");
            }
            else {
                $('#modelView').html(data);
            }
        });
    }
</script>

In the main layout (which this partial view uses) I have these scripts named in the header:

<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

It should also be noted that when the submit button is clicked, I want to put the partial view being returned from the server in the element named "modelView" located in the main view, if there are validation errors (and I have verified from looking in the data parameter that there is). I want to redirect if there are no validation errors. The 'if' statement is always true whether I produce validation errors or not, which means it's not finding any spans with the given type of class.

I thought the selector was wrong at first, but I tried lots of things and the internet seems to say what I have is the correct way. So I thought there might be another problem.

Any help is greatly appreciated, thank you.

L_Laxton
  • 67
  • 1
  • 7

1 Answers1

0

Have you tried changing your jQuery to use the find function?

It appears that jQuery (or the browser itself) strips out the <html> and <body> tags, as mentioned here: Using jQuery to search a string of HTML

<script type="text/javascript">
    function submit_onClick()
    {
        $.ajax({
            method: "POST",
            url: "/Projects/CreateProject",
            cache: false
        }).success(function (data) {
            if ($(data).find('span[class="field-validation-error"]').length == 0) {
                window.location.assign("/Projects/Index");
                alert("New Project request submitted successfully.");
            }
            else {
                $('#modelView').html(data);
            }
        });
    }
</script>

You could also try:

if ($('span[class="field-validation-error"]', $(data)).length == 0) {}
Community
  • 1
  • 1