How do I render a partial form element using AJAX
Asked Answered
U

2

2

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.

Unheard answered 28/10, 2013 at 19:53 Comment(1)
I have learned more about sending information back to the controller. Please see my update in my answer below to see if that helpsAguirre
A
7

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.

Aguirre answered 28/10, 2013 at 19:59 Comment(2)
No other way to reference the model huh?Unheard
You could serialize the model object to the data property using: data: @Html.Raw(Json.Encode(Model)),Manofwar
J
0

You need to add the properties of the model for the controller you are calling in the ajax request. In this case your AddPreferencecontroller has a parameter of type FormViewModel. I assume the information for the FormViewModel is stored on the page. You need to pass those in the data property for the ajax request.

If you post your FormViewModel properties I could help futher. Bascially you need to the following:

$('#addPreference').click(function () {

    $.ajax({
        type: "POST",
        url: '@Html("AddPreference", "Main")',
        data: {id: "123asd", Prop1: myProp1},
        success: function (html) {
            $(html).appendTo('#additionalPreference');
            console.log(html);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Error");
        },
        complete: function () {
            console.log("End");
        }
    });

Post more information of your model and the view you are making the ajax request and I can assist further.

Jacaranda answered 28/10, 2013 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.