How do I render a partial form element using AJAX
Solution 1:
For an ajax call you have to build the model:
$.ajax({
type: "POST",
url: '@Url.Action("AddPreference", "Main")',
data: {
Field1: 'field1',
Field2: 'field2'
},
success: function (html) {
$(html).appendTo('#additionalPreference');
console.log(html);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
complete: function () {
console.log("End");
});
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:
@Html.Raw(Json.Encode(Model))
I have found out about serialize and we use:
$('form').serialize()
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.