【问题标题】:Problems passing a Model from a View to a Controller将模型从视图传递到控制器的问题
【发布时间】:2013-02-21 15:31:08
【问题描述】:

我将我的Checkout 视图与我想传递给我的Purchase 控制器的模型绑定 绑定到我的Purchase 视图。 在它被传递的那一刻,它的值为null。

我做错了什么?

结帐视图:

@model List<BasketModels.Product>

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

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

采购控制人:

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

产品模式:

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; }
        }
}

【问题讨论】:

  • 你能把你的提交按钮简化为&lt;input type="submit" value="submit" /&gt;,看看你的进展如何?你不应该在那里需要所有 JS 重定向的东西
  • 我认为使用 DisplayFor 不会填充您的模型
  • @CrazyCoderz 那行不是问题,它是底部的提交按钮
  • 提交按钮中的 onclick 事件已损坏。提交按钮不需要点击处理程序。如果您单击提交按钮,浏览器会将数据发布到您在表单元素的 action 属性中设置的 url。在你的情况下,mvc 在 Html.BeginForm 为你做这件事
  • @Oliver 我按照 Vazes 的评论删除了那部分,但它仍然是空的。

标签: c# unit-testing asp.net-mvc-4


【解决方案1】:

您可以使用@Html.HiddenFor(x=>x.modelPropery) 快速而肮脏的路线。这是对您的 DisplayFor 的补充。

【讨论】:

  • 那行不是问题,是底部的提交按钮
【解决方案2】:

我使用以下方法对其进行了测试,它可以工作。

结帐视图

@model ProjectName.Models.BasketModels.Product

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

购买的控制器

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

我知道您可能仍希望将其绑定为列表。在那种情况下,我几天来一直试图弄清楚如何做到这一点,但我没有解决方案。 List&lt;string&gt; 有效。 List&lt;model&gt; 没有。

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    相关资源
    最近更新 更多