简体   繁体   English

如何将 IEnumerable 从 View 发送回 Controller

[英]How to send IEnumerable back from View to Controller

I'm pretty new to MVC and ASP.Net, my controller has 2 create methods for GET and POST.我对 MVC 和 ASP.Net 很陌生,我的 controller 有 2 种用于 GET 和 POST 的创建方法。 Through the Get method I'm generating a list and sending it into the view.通过Get方法,我正在生成一个列表并将其发送到视图中。 In the view I'm making changes to a specific value in each var in the list and trying to send it back to the controller and the POST method.在视图中,我正在更改列表中每个 var 中的特定值,并尝试将其发送回 controller 和POST方法。

When reaching the Post method, the value of the list is null.到达Post方法时,列表的值为 null。

The list I'm sending is a list of products and I'm using a view model to create a class with common values to pass through to the view.我发送的列表是产品列表,我正在使用视图 model 创建一个 class 具有公共值以传递到视图。

To pass through the IEnumerable collection that was edited by the view I tried using BeginCollectionForm , setting the items through ViewBag , make changes to the model ( @model IEnumerable<MarsBurgerV1.ViewModel.ItemVM> ), but still each time the checkout button is being pressed the list in the Post method is NULL.要通过由我尝试使用BeginCollectionForm的视图编辑的IEnumerable集合,通过ViewBag设置项目,对 model ( @model IEnumerable<MarsBurgerV1.ViewModel.ItemVM> )进行更改,但每次结帐按钮仍然是按Post方法中的列表是 NULL。

After a lot of tries and changes, currently my code looks as the following:经过大量尝试和更改,目前我的代码如下所示:

OrderController.cs (relevant parts) OrderController.cs (相关部分)

public class OrderController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    public ActionResult Create()
    {
        var meals = (from m in db.meals
                     select new ItemVM
                     {
                         Id = m.Id,
                         Name = m.Name,
                         Price = m.Price,
                         ItemType = "Meal",
                         ImageURL = m.ImageUrl,
                         Quantity = 0
                     }).ToList();
        var drinks = (from d in db.drinks
                      select new ItemVM
                      {
                          Id = d.Id,
                          Name = d.Name,
                          Price = d.Price,
                          ItemType = "Drink",
                          Quantity = 0
                      }).ToList();
        //More Like That....
        List<ItemVM> items = new List<ItemVM>();
        items.AddRange(meals);
        items.AddRange(drinks);//More Like...
        return View(items.ToList());
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(IEnumerable<ItemVM> items = null)
    {
        //Here items equals to null.
        if (ModelState.IsValid) 
        {
           //.....
        }
        return View();
    }

Views/Order/Create.cshtml:视图/订单/Create.cshtml:

@model IEnumerable<***.ViewModel.ItemVM>

@{
    ViewBag.Title = "Create";
    var lst = Model.ToList();
    ViewBag.List = Model.ToList();
}
<style>
    tr td {
        vertical-align: middle;
    }
</style>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <h3> Order:</h3>
    <table class="table table-condensed table-hover">
        <tr calss="table-header">
            <th>
                @Html.DisplayName("Preview")
            </th>
            <th>
                @Html.DisplayNameFor(m => m.Name)
            </th>
            <th>
                @Html.DisplayNameFor(m => m.Price)
            </th>
            <th>
                @Html.DisplayName("Quantity")
            </th>
            <th></th>
            <th></th>
        </tr>
        @for (var i = 0; i < Model.Count(); i++)
        {
            <tr>
                <td>
                    @if (Model.ElementAt(i).ImageURL != null)
                    {
                        <img src="@Url.Content(Model.ElementAt(i).ImageURL)" alt="IMAGES" height="100" width="100" />
                    }
                </td>
                <td>
                    @Html.DisplayFor(m => Model.ElementAt(i).Name)
                </td>
                <td>
                    @Html.DisplayFor(m => Model.ElementAt(i).Price)
                </td>
                <td>
                    <a type="button" class="btn btn-danger btn-xs" href="#">
                        <span class="glyphicon glyphicon-minus"></span>
                    </a>
                    @Html.EditorFor(l => lst[i].Quantity, new { htmlattribute = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => lst[i].Quantity, "", new { @class = "text-danger" })
                    <a type="button" class="btn btn-success btn-xs" id="plus" href="#">
                        <span class="glyphicon glyphicon-plus"></span>
                    </a>
                </td>
            </tr>
        }
    </table>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Checkout" class="btn btn-primary"/>
    </div>
</div>
}

ViewModel/ItemVM.cs: ViewModel/ItemVM.cs:

namespace ***.ViewModel
{
    public class ItemVM
    {
        [Required]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        [DataType(DataType.Currency)]
        public double Price { get; set; }
        [Required]
        public string ItemType { get; set; }
        
        public string ImageURL { get; set; }
        [Required]
        public int Quantity { get; set; }
    }
}

In the end I want to use the "Create" ( HttpPost method) to create a new order based on the values in the list received from the view.最后,我想使用“创建”( HttpPost方法)根据从视图接收到的列表中的值创建新订单。

What is the proper way of doing that and receiving the IEnumerable into the POST method?这样做并将IEnumerable接收到POST方法中的正确方法是什么?

Ok, I was finally able to make it work.好的,我终于能够让它工作了。 I've changed the @model to List Type, Add the (actionName, Controller, FormMethod) to the HTML Helper Html.BeginForm , Used Model[i] inside the loop to access variables and marked all unchanged variables with @Html.HiddenFor.我已将@model更改为 List 类型,将(actionName, Controller, FormMethod)添加到@Html.HiddenFor. Helper Html.BeginForm和标记的所有变量到循环中未更改的变量Model[i]

Create.cshtml:创建.cshtml:

@model List<MarsBurgerV1.ViewModel.ItemVM>
@{
    ViewBag.Title = "Create";
}
@using (Html.BeginForm("Create","Order", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <h3> Order:</h3>
    <table class="table table-condensed table-hover">
        <tr calss="table-header">
            <th>
                @Html.DisplayName("Preview")
            </th>
            <th>
                @Html.DisplayName("Name")
            </th>
            <th>
                @Html.DisplayName("Price")
            </th>
            <th>
                @Html.DisplayName("Quantity")
            </th>
            <th></th>
            <th></th>
        </tr>
        @for (var i = 0; i < Model.Count(); i++)
        {
        <tr>
            @Html.HiddenFor(m => Model[i].Id)
            @Html.HiddenFor(m => Model[i].Type)
            <td>
                @Html.HiddenFor(m => Model[i].ImageURL)
                @if (Model[i].ImageURL != null)
                {
                    <img src="@Url.Content(Model[i].ImageURL)" alt="IMAGES" height="100" width="100" />
                }
                @Html.ValidationMessageFor(model => Model[i].ImageURL, "", new { @class = "label-control" })
            </td>
            <td>
                @Html.HiddenFor(m => Model[i].Name)
                @Html.DisplayFor(m => Model[i].Name)
                @Html.ValidationMessageFor(model => Model[i].Name, "", new { @class = "label-control" })
            </td>
            <td>
                @Html.HiddenFor(m => Model[i].Price)
                @Html.DisplayFor(m => Model[i].Price, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => Model[i].Price, "", new { @class = "label-control" })
            </td>
            <td>
                <a type="button" class="btn btn-danger btn-xs" href="#">
                    <span class="glyphicon glyphicon-minus"></span>
                </a>
                @Html.EditorFor(model => Model[i].Quantity, new { htmlattribute = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => Model[i].Quantity, "", new { @class = "text-danger" })
                <a type="button" class="btn btn-success btn-xs" id="plus" href="#">
                    <span class="glyphicon glyphicon-plus"></span>
                </a>
            </td>
        </tr>
        }
    </table>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <button type="submit" value="Checkout" class="btn btn-primary"/>
    </div>
</div>
}

Thanks Everyone for the help.谢谢大家的帮助。

暂无
暂无

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

相关问题 IEnumerable数据未从视图传递回控制器 - IEnumerable data not passing back from view to controller 查看创建发送IEnumerable到Controller - View Create send IEnumerable to Controller 从控制器获取数据到视图后,如何将数据发送回视图 - After getting the data from controller to view, how to send back the data to the view 如何将列表中视图中选择的值的IEnumerable返回给控制器 - How to return to controller a IEnumerable of the values selected in the view from a list 如何从控制器到视图传递一行数据,而不是IEnumerable &lt;&gt; - How to pass one row of data from controller to view , not as IEnumerable<> 如何在MVC中使用IEnumerable模型将数据从控制器传递到视图? - How to pass Data from Controller to View with IEnumerable Model in MVC? 如何将多个自动生成的字段中的数据从视图发送回控制器 - How to send back data from multiple auto-generated fields from view to controller 如何将包含两个列表的模型从视图发送回控制器 - How can i send back a model containing two lists from the view to my controller 如何从一个控制器重定向到另一个控制器并将响应发送回mvc4中的原始视图? - how to redirect from one controller to another with object and send response back to original view in mvc4? 将数据从控制器传输到视图-List &lt;&gt; / IEnumerable &lt;&gt;? - Transferring data from controller to view - List<> / IEnumerable<>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM