简体   繁体   English

将模型从视图传递到控制器时出现问题

[英]Problems passing a Model from a View to a Controller

I bind my Checkout View with a Model which I'd like to pass to my Purchase controller to bind to my Purchase View. 我将Checkout View与要传递给我的Purchase控制器的模型绑定,以绑定到我的Purchase View。 At the moment when it gets passed, the value is null. 在通过时,该值为null。

What am I doing wrong? 我究竟做错了什么?

Checkout View: 结帐视图:

@model List<BasketModels.Product>

@using (Html.BeginForm("Purchased", "Basket", FormMethod.Post))
{

// problem here
    <input type="submit" value="Purchase"/>
}

Purchase controller: 采购主管:

[HttpPost]
        public ActionResult Purchased(List<BasketModels.Product> products)

Product mode: 产品模式:

public class BasketModels
    {
        public class Product
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }

            [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
            public decimal UnitPrice { get; set; }

            public string ImageURL { get; set; }

            [Display(Name = "Quantity")]
            public int Quantity { get; set; }


            public int Stock { get; set; }

            [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
            public decimal Price { get; set; }

            [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
            public decimal TotalPrice { get; set; }
        }
}

You can use @Html.HiddenFor(x=>x.modelPropery) quick and dirty route. 您可以使用@ Html.HiddenFor(x => x.modelPropery)快速而肮脏的路线。 This is in adittion to your DisplayFor. 这符合您的DisplayFor。

I tested it using the following and it works. 我使用以下方法对其进行了测试,并且可以正常工作。

Checkout View 结帐视图

@model ProjectName.Models.BasketModels.Product

@using (Html.BeginForm("Purchased", "Basket", FormMethod.Post))
{
    @Html.TextBoxFor(m=>m.Description)
    <input type="submit" value="Purchase"/>
}

Purchased Controller 购买的控制器

[HttpPost]
public ActionResult Purchased(BasketModels.Product products)
{
     return View();
}

I realize you might still want it to bind as a list. 我意识到您可能仍然希望将其绑定为列表。 In that case, I've been trying to figure how to do that for days and I don't have a solution. 在那种情况下,我几天来一直在试图解决该问题,但我没有解决方案。 List<string> works. List<string>有效。 List<model> does not. List<model>没有。

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

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