views:

2546

answers:

4

I am using jQuery.load() to render a partial view. This part looks like this:

$('#sizeAddHolder').load(
                '/MyController/MyAction', function () { ... });

The code for actions in my controller is the following:

    public ActionResult MyAction(byte id)
    {
        var model = new MyModel
        {
            ObjectProp1 = "Some text"
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult MyAction(byte id, FormCollection form)
    {
        // TODO: DB insert logic goes here

        var result = ...;

        return Json(result);
    }

I am returning a partial view that looks something like this:

<% using (Html.BeginForm("MyAction", "MyController")) {%>
    <%= Html.ValidationSummary(true) %>

    <h3>Create my object</h3>

    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.ObjectProp1) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.Size.ObjectProp1) %>
            <%= Html.ValidationMessageFor(model => model.ObjectProp1) %>
        </div>

        div class="editor-label">
            <%= Html.LabelFor(model => model.ObjectProp2) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(model => model.ObjectProp2) %>
            <%= Html.ValidationMessageFor(model => model.ObjectProp2) %>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

Client side validation does not work in this case. What is more the script that contains validation messages also isn't included in the view that's returned. Both properties in my model class have Required and StringLength attributes. Is there any way to trigger client side validation in a view which has been loaded like this?

+3  A: 

First of all you should return a partial view and not a view.

return PartialView(model);

Second, are you trying to load this partial view with AJAX? In that case you might want to use jquery.ajax

function ajax_update(path)
  $.ajax {
    url: path,
    success: function(result) {
      $('#sizeAddHolder').html(result);
    }
  return false;
}
Flexo
Thank you for valuable info. I've corrected these errors but that doesn't really make a difference. The rendered html is exactly the same in both cases since `load()` gets the html the same way that `ajax()` does using XMLHttpRequest and `return View(model)` if theres no SomeAction.aspx will render SomeAction.ascx. Take a look here: http://stackoverflow.com/questions/2043394/what-is-the-difference-between-a-view-and-a-partialview-in-asp-net-mvcSo the main problem is still there: no client side validation; no script containing validation messages..
brainnovative
The above code doesn't solve the original problem
Shay Erlichmen
@Flexo he can return a View also, it doesn't really matters as long as the view that he is returning is not using the same masterpage as the one where it is called
Omu
+1  A: 

You should use dataType on the ajax call

function ajax_update(path)
  $.ajax {
    url: path,
    dataType: "html",
    success: function(result) {
      $('#sizeAddHolder').html(result);
    }
  return false;
}

From jQuery docs:

dataType Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

* "xml": Returns a XML document that can be processed via jQuery.
* "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
* "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
* "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
* "jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.
* "text": A plain text string.
Rafael Mueller
Thanks for this info.The thing is that in one case I'd like to return html (when the data passed wasn't valid - since client side validation fails..) so the user can make changes and post it again. But when the data validated and a new object in the database was created successfully then I'd like to return Json. Is there any way to check the type of returned result?
brainnovative
Try setting the MIME type of response:*If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response*
Rafael Mueller
+1  A: 

I'm not sure if you are still loking for answer to your question, but I have write a post about making AJAX loaded forms work with client-side validation in ASP.NET MVC 2: http://tpeczek.blogspot.com/2010/04/making-aspnet-mvc-2-client-side.html

tpeczek
A: 

The problem is that the form loaded with ajax never gets registered with the Microsoft validation. To solve it call the following function Sys.Mvc.FormContext._Application_Load.

function ajax_update(path)
  $.ajax {
    url: path,
    success: function(result) {
      $('#sizeAddHolder').html(result);
      Sys.Mvc.FormContext._Application_Load();
    }
  return false;
}

That should fix it. Also, make sure that the forms you load via ajax have unique id's. Otherwise, the validation will fail.

Avoid using load(). It removes any scripts loaded in the response.

jcruz