why do I have to match the parameter name to get json data from ajax call in MVC4 web app?

后端 未结 2 1271
眼角桃花
眼角桃花 2021-01-17 06:54

I just want to know why it\'s necessary for .NET to match parameter name with the JSON object\'s key name?

Quick code preview here...

var json = {
           


        
相关标签:
2条回答
  • 2021-01-17 07:39

    Base on post MVC controller : get JSON object from HTTP body? You action should be:

    [HttpPost]
    public ActionResult DATACRUD()
    {
        Stream req = Request.InputStream;
        req.Seek(0, System.IO.SeekOrigin.Begin);
        string json = new StreamReader(req).ReadToEnd();
        return Json(new { fromMVC = json });
    }
    
    0 讨论(0)
  • 2021-01-17 08:01

    The MVC routing engine dictates that the parameter names must match, as that is how it knows what to populate since everything comes through as strings to the server. The MVC plumbing will be searching through the query portion of the URL, and even searching fields in a form on a POST to populate all of your parameters.

    Having a hundred models is not that bad for a complex project. However, it can be a pain if you have to go back and retrofit your entire application.

    No matter what you do, you'll need to make sure that your JavaScript variable names match those of your Action method parameters, which shouldn't be a problem since you're writing both sides.

    0 讨论(0)
提交回复
热议问题