I have a form that assembles sections of a larger form. For example:
Html.RenderPartial("Partials/MealPreference", Model);
I would like to dynamically add sections to the form. Given the nature of my partial views, I must pass the model along as well. In that, I am failing miserably.
The markup on my containing page:
<div id="additionalPreference"></div>
<input type="button" value="Add Additional Preference" id="addPreference" />
<script>
$(document).ready(function () {
$('#addPreference').click(function () {
$.ajax({
type: "POST",
url: '@Html("AddPreference", "Main")',
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
}
});
});
});
</script>
My controller action:
[HttpPost]
public ActionResult AddPreference(FormViewModel model)
{
if (ModelState.IsValid)
{
return PartialView("Partials/AdditionalPreference", model);
}
else
{
return PartialView("Partials/LoadFailed");
}
}
The model is never valid. How do I pass the model form the containing page to the controller action? This would seem to be something simple to do (it certianly would be in Web Forms) but I have been choking on this for 3 hours.
You need to add the properties of the model for the controller you are calling in the ajax request. In this case your
AddPreference
controller has a parameter of typeFormViewModel
. I assume the information for theFormViewModel
is stored on the page. You need to pass those in thedata
property for the ajax request.If you post your
FormViewModel
properties I could help futher. Bascially you need to the following:$('#addPreference').click(function () {
Post more information of your model and the view you are making the ajax request and I can assist further.
For an ajax call you have to build the model:
Make sure that the names in the data section of the ajax call match exactly the names in your model and it should show up in your controller populated.
update:
Since writing this answer I have learned more about sending information back to the controller via ajax. As commented by Rick Dailey you can send the model submitted to the form back to the controller via:
I have found out about serialize and we use:
To send the fields on the form back to the controller. A quick, easy way to send all information back similar to a post back without having to manually build the model.