简体   繁体   English

如何将Javascript数组获取到MVC控制器

[英]How to get Javascript array to MVC controller

I am building a asp.net application where users can order food, and i also have a admin page where the admins can login and make a menu for a specific week. 我正在构建一个asp.net应用程序,用户可以在其中订购食物,还拥有一个管理员页面,管理员可以在该页面登录并在特定星期内制作菜单。 I have solved everything inside that "Menu maker" and when i press the Save button every value from the menu goes into a javascript array. 我已经解决了“菜单制作器”中的所有问题,并且当我按下“保存”按钮时,菜单中的每个值都进入了一个javascript数组。

So to the problem. 所以要解决这个问题。 When i press the save button I want to serialize the array to json to then be able to pass it over to my mvc controller. 当我按下保存按钮时,我想将数组序列化为json,然后将其传递给我的mvc控制器。

I am trying to do that with ajax. 我正在尝试使用Ajax。 This is the full code of the save button click: 这是保存按钮单击的完整代码:

$("#CreateMenuBtn").on('click', function () {
FullMenu.push(
    {
        "Year": $("#YearInput").val(),
        "Week": $("#WeekInput").val(),
        "Products": MenuArray
    }
);
var dataToPost = JSON.stringify({ methodParam: FullMenu });

$.ajax({
    type: "POST",
    url: '@Url.Action("Index", "Home")',
    contentType: "application/json; charset=utf-8",
    dataType: 'JSON',
    data: dataToPost,
    traditional: true
});
console.log(FullMenu);
});

When i now debugg and check the value of data it is perfectly right and in JSON format: 当我现在调试并检查data值时,它是完全正确的并且采用JSON格式:

methodParam
 [0]
   Year: "2019"
   Week: "4"
   Products:
   [0]
      WeekDay: "Måndag"
      Food: "kött"
      Price: "54kr"
      Cabinet: "C"
   [1]
      Weekday: "Onsdag"
      Food: "Köttbullar"
      Price: "80kr"
      Cabinet: "B"

Now I want it to my mvc controller. 现在,我想将其发送给我的MVC控制器。

I have a classes called Menu and Product it looks like this: 我有一个叫做MenuProduct的类,它看起来像这样:

public class Menu
{
    public int ID { get; set; }

    public string Year { get; set; }

    public string Week { get; set; }

    public virtual List<Product> Products { get; set; }

}



public class Product
{
    public int ID { get; set; }

    public string Description { get; set; }

    public int Price { get; set; }

    public char Cabinet { get; set; }

    public int MenuID { get; set; }

    public int Day { get; set; }
}

This is what i came up with in the controller: 这是我在控制器中想到的:

    public IActionResult Index(List<Menu> methodParam)
    {
       foreach(Menu item in methodParam)
        {
            string des = item.Week + item.Year;
        }
        return View();
    }

But when i debugging inside the action inside the foreach loop, methodParam gets the value 0. 但是当我在foreach循环内的动作中进行调试时, methodParam的值为0。

So what i want help with is how I can get the array into c#. 因此,我需要帮助的是如何将数组放入C#。 I hope that explains my situation, would appreciate som help. 我希望这能解释我的情况,希望能得到som的帮助。

Thanks in advance! 提前致谢!

Try this, 尝试这个,

 var FullMenu = [];
        var Menu1 = {};
        Menu1['Year'] = "2016",
            Menu1['Week'] = "Jan";
        FullMenu.push(Menu1);
        var Menu2 = {};
        Menu2['Year'] = "2017",
            Menu2['Week'] = "Feb";
        FullMenu.push(Menu2);
        var dataToPost = FullMenu;
        $.ajax({
            url: '@Url.Action("Index", "Home")',
            type: 'POST',
            data: {
                methodParam: dataToPost
            },

first of all try to make c# classes structure same as json object same properties names then try 首先尝试使c#类结构与json对象具有相同的属性名称,然后尝试

public IActionResult Index(string methodParam)
    {
       List<Menu> menu = new JavaScriptSerializer().Deserialize<Menu>(methodParam);
       foreach(Menu item in menu)
        {
            string des = item.Week + item.Year;
        }
        return View();
    }

This solved the problem :D Changed the url to /Home(Controller name)/Index(Action name) 这解决了问题:D将url更改为/Home(Controller name)/Index(Action name)

var dataToPost = JSON.stringify(jsonData);

$.ajax({
    type: "POST",
    url: '/Home/Create',
    contentType: "application/json; charset=utf-8",
    dataType: 'JSON',
    data: dataToPost,
    traditional: true
});

And the action needed to have [FromBody] like this: 并且需要使[FromBody]像这样执行操作:

[HttpPost]
public IActionResult Create([FromBody] Dictionary<string, object> jsonMenu)
{
    //Code
    return RedirectToAction("Index", "Home");
}

Thanks a lot to you guys who tried to help :) 非常感谢你们试图帮助的人:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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