Home > Blockchain >  AJAX hiddenfield submit instead of form does not work
AJAX hiddenfield submit instead of form does not work

Time:10-14

I have trouble sending AJAX post request to controller. The following code works:

var path = $(this).prop("value");

                    var token = $('[name=__RequestVerificationToken]').val();
                    var headers = {};
                    headers["__RequestVerificationToken"] = token;

                    var ids = $("#ids").val();

                    
                    var formData = new FormData();
                    formData.append('ids', ids);


                    $.ajax({
                        url: path,
                        type: "POST",
                        cache: false,
                        headers: headers,
                        data: formData,
                        async: false,
                        processData: false,
                        contentType: false,
                        success: function (result) {
                            document.write(result);
                            document.close();
                            console.log("YES");
                        },
                        error: function () {
                            alert("Error.");
                            
                        }
                    });

Here is the Controller Method:

    [AjaxOnly]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
        public ActionResult MyMethod(string aString)

The call to the Controller works fine, but as expected aString in Controller-Function parameter is null.

What I actually want to do is not to POST the formData ($("#myForm").serialize();) in the data field of the AJAX post, but an hiddenField:

    var aString = $("#ids").val();

So when I put the aString variable in the data field of Ajax call instead of formData the call to my function does not work anymore and I get 500 error.

Anyone can help how to POST this hiddenfield value instead of formData?

MyForm:

@{
    ViewBag.Title = "MyForm";
    @model MyFormModel
}
@using (Html.BeginForm("MyForm", "MyController", FormMethod.Post, new { id = "MyForm" }))
{
 <div  id="tabContent">
content
</div>
   @Html.Partial("_MyFormPopup")

Partial:

@using (Html.BeginForm("MyMethod", "MyController", FormMethod.Post))
{
    @Html.AntiForgeryToken()
 <div >
content
</div>
  @Html.Hidden("ids")

Controller Code:

    [AjaxOnly]
            [HttpPost]
            [ValidateAntiForgeryToken]
            [OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
            public ActionResult MyMethod(string ids)
            {
               
    
                string[] IdsFunktions = ids.Split(new string[] { ";" }, 
    
                ....
     return RedirectToAction("MyForm");
}


       

CodePudding user response:

So in order for your code to work you need to correctly name your formData variables, here are the two variants:

If you want to have a aString variable on your Controller then your AJAX post code should post like this:


var formData = new FormData();
formData.append('aString', $("#ids").val());

$.ajax({
  url: path,
  type: "POST",
  cache: false,
  headers: headers,
  data: formData,
  async: false,
  success: function (result) {
    document.write(result);
    document.close();      
  },
  error: function () {
    alert("Error.");
  }
});

Another solution would be in the case you want to post all form fields data by using data: $("#myForm").serialize() you must change the Controller reference variable names and reference each field by its form name, e.g if you have only one hidden field then:

[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult MyMethod(string ids, string fieldNameOne, string fieldNameTwo, etc...)

  • Related