How do I render a partial form element using AJAX

泄露秘密 提交于 2019-12-17 04:08:31

问题


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.


回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/19643864/how-do-i-render-a-partial-form-element-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!