MVC 2 Ajax.Beginform passes returned Html + Json to javascript function
- by Joe
Hi,
I have a small partial Create Person form in a page above a table of results. I want to be able to post the form to the server, which I can do no problem with ajax.Beginform.
<% using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "ProcessResponse" }))
{%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%=Html.LabelFor(model => model.FirstName)%>
</div>
<div class="editor-field">
<%=Html.TextBoxFor(model => model.FirstName)%>
<%=Html.ValidationMessageFor(model => model.FirstName)%>
</div>
<div class="editor-label">
<%=Html.LabelFor(model => model.LastName)%>
</div>
<div class="editor-field">
<%=Html.TextBoxFor(model => model.LastName)%>
<%=Html.ValidationMessageFor(model => model.LastName)%>
</div>
<p>
<input type="submit" />
</p>
</fieldset>
<%
}
%>
Then in my controller I want to be able to post back a partial which is just a table row
if the create is successful and append it to the table, which I can do easily with jquery.
$('#personTable tr:last').after(data);
However, if server validation fails I want to pass back my partial create person form with the validation errors and replace the existing Create Person form.
I have tried returning a Json array
Controller:
return Json(new
{
Success = true,
Html= this.RenderViewToString("PersonSubform",person)
});
Javascript:
var json_data = response.get_response().get_object();
with a pass/fail flag and the partial rendered as a string using the solition below but that doesnt render the mvc validation controls when the form fails.
SO RenderPartialToString
So, is there any way I can hand my javascript the out of the box PartialView("PersonForm") as its returned from my ajax.form? Can I pass some addition info as a Json array so I can tell if its pass or fail and maybe add a message?
UPDATE
I can now pass the HTML of a PartialView to my javascript but I need to pass some additional data pairs like ServerValidation : true/false and ActionMessage : "you have just created a Person Bill". Ideally I would pass a Json array rather than hidden fields in my partial.
function ProcessResponse(response) {
var html = response.get_data();
$("#campaignSubform").html(html);
}
Many thanks in advance