ASP.NET MVC 2 loading partial view using jQuery - no client side validation

Maksymilian Majer picture Maksymilian Majer · Apr 16, 2010 · Viewed 23.9k times · Source

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?

Answer

Flexo picture Flexo · Apr 16, 2010

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;
}