Post ajax data to MVC controller

Viewed 37

I have the following ajax in a .chtml file:

    var planID = $("#PlanID").val();
    if (planID.length == 4) {
        $(ctl).prop("disabled", true).text(msg);
        $("#nextButton").prop("disabled", true);
        setTimeout(function () {
            $(".submit-progress").removeClass("hidden");
        }, 1);
        $.ajax({
            type: "POST",
            url: "/ForgotUserID/CheckPlanID",
            data: '{planID: "' + planID + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                console.log("ajax success function");
                $("form").submit();
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
        //$("form").submit()
    }

And I have the following in my ForgotUserIDController:

    [HttpPost]
    public JsonResult CheckPlanID(string planID)
    {
        ForgotUserID forgotUserID = new ForgotUserID()
        {
            PlanID = planID
        };

        return Json(forgotUserID);
    }

When I run the code, I see this in the dev tools under network:

enter image description here

So I know the data that I typed into my input box is floating around somewhere.

When I have a breakpoint set in my controller, the value of planID is null. Shouldn't the value get passed from the ajax data component?

How can I get the data typed into the input box passed to my controller?

Any assistance is greatly appreciated.

Thank you!

1 Answers

if you want to use contentType: "application/json; charset=utf-8",

fix ajax data line

 data: JSON.stringify({ planID : planID  }),

and create viewmodel and use frombody attribute in action

 public JsonResult CheckPlanID([FromBody] PlanViewModel model)
{
       string planID=model.PlanID;
      ....
}

public class PlanViewModel
{
  public string PlanID {get;set;}
}

or remove contentType: "application/json; charset=utf-8" and fix data

//contentType: "application/json; charset=utf-8",

data: { planID : planID  },

in this case you don't need and extra class and frombody attribute. Leave your action header as it is

Related