How do I render a partial form element using AJAX

2019-01-04 14:29发布

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.

2条回答
霸刀☆藐视天下
2楼-- · 2019-01-04 14:46

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.

查看更多
老娘就宠你
3楼-- · 2019-01-04 15:05

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.

查看更多
登录 后发表回答