简体   繁体   中英

How to pass MVC view model into AJAX call with AntiForgeryToken

The code below is working for me, but I'm trying to find a way to read all values from the form instead of having to re-create the view model in JavaScript (vm is the name of the parameter of the object).

I tried to serialize the form and pass it in, but maybe my syntax is incorrect.

Any suggestions?

 $.ajax({ type: "POST", dataType: "json", url: "/post-details-save", data: addAntiForgeryToken({ vm: ({ Id: $("#PostImageDetails_Id").val(), Title: $("#PostImageDetails_Title").val(), Description: $("#PostImageDetails_Description").val(), CopyrightOwner: $("#PostImageDetails_CopyrightOwner").val(), CopyrightUrl: $("#PostImageDetails_CopyrightUrl").val(), SourceName: $("#PostImageDetails_SourceName").val(), SourceUrl: $("#PostImageDetails_SourceUrl").val(), SourceLicenseType: $("#PostImageDetails_SourceLicenseType").val() }) }), success: postDetailsSaveSuccess, error: postDetailsSaveError }); 

Confirm Form Setup

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @id = "formID" }))

I have done similar stuff with submitting forms in partial views.

Basically, you need to confirm that your html form is set up correctly:

The AntiForgeryToken

@Html.AntiForgeryToken()

Data Fields

Could look something like the following with the name attribute being important.

<input type="hidden" name="ApproveUserID" id="ApproveUserID" value="@Model.ApproveUserID" />

AJAX The Form

If your form is set up correctly like explained above, you will be able to submit the data via AJAX with something similar to the JS below.

var form = $("#formID");
$.ajax({
    url: form.attr('action'),
    type: form.attr('method'),
    data: form.serialize(), // data to be submitted
    success: function (response) {
        if (response == "Success") {
            //DO SUCCESS STUFF
        } else
        {
            //DO FAILURE STUFF
        }
    },
    error: function () {
            //DO ERROR STUFF
    }
});

Pro Tip:

You can always expand the data you send by placing

var formData = form.serialize();

Into a variable and expanding it from there.

Good Luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM