简体   繁体   中英

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. 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.

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.

I am trying to do that with 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:

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.

I have a classes called Menu and Product it looks like this:

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.

So what i want help with is how I can get the array into c#. I hope that explains my situation, would appreciate som help.

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

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)

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:

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

Thanks a lot to you guys who tried to help :)

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