【发布时间】:2010-10-02 00:41:37
【问题描述】:
我正在尝试将 viewModel 传递给编辑表单视图。问题是我实例化了模型并为其赋值,但模型仍然为空。
我的行动:
public ActionResult OrderEdit(takeOrder FormInput)
{
takeOrder viewModel = new takeOrder
{
Name= "anonymous",
TableNumber = 13,
FoodItems = new List<FoodItem> {
new FoodItem{ DishName = "Dishname value 1", Price = 10 },
new FoodItem{ DishName = "Dishname value 2", Price = 20 },
new FoodItem{ DishName = "Dishname value 3", Price = 30 },
new FoodItem{ DishName = "Dishname value 4", Price = 40 },
}
};
if (FormInput != null)
viewModel = FormInput;
return View(viewModel);
}
我的观点是这样的:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/genesis.Master" Inherits="System.Web.Mvc.ViewPage<Genesis_0_02.Models.takeOrder>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
OrderEdit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>OrderEdit</h2>
<% using (Html.BeginForm())
{ %>
<%: Html.ValidationSummary() %>
<p>
<%: Html.LabelFor(x => x.Name) %><br />
<%: Html.TextBoxFor(x => x.Name) %>
</p>
<p>
<%: Html.LabelFor(x => x.TableNumber) %><br />
<%: Html.TextBoxFor(x => x.TableNumber) %>
</p>
<button type="button" id="AddListItem">Add a dish to your order</button>
<br />
<% for (int i = 0; i < Model.FoodItems.Count(); i++ )%>
<% { %>
<div class="ListItem">
<button type="button" class="RemoveListItem">X</button>
Dish: <%: Html.TextBoxFor(x => x.FoodItems[i].DishName, new { style = "width:60px;" } )%>
Price: <%: Html.TextBoxFor(x => x.FoodItems[i].Price, new { style = "width:60px;" })%>
</div>
<% } %>
<br />
<button type="submit">Submit Order</button>
<% } %>
</asp:Content>
我得到的错误是:
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: source
Source Error:
Line 64: <button type="button" id="AddListItem">Add a dish to your order</button>
Line 65: <br />
--> error --> Line 66: <% for (int i = 0; i < Model.FoodItems.Count(); i++ )%>
Line 67: <% { %>
Line 68: <div class="ListItem">
Source File: pathtotheproject\Genesis.0.02\Genesis.0.02\Views\Admin\OrderEdit.aspx Line: 66
我在我的操作OrderEdit 中在viewModel 上添加了一个断点,并且所有值都作为空值传递给视图。我不明白这一点,因为我对每个参数的值进行了硬编码。
为什么我的viewModel 为空?
编辑
我确实有 javascript 可以在表单中添加菜肴。我从上面列出的视图中删除了它,因为它与错误无关。
编辑:回复@Loki Stormbringer 的回答
public ActionResult OrderEdit(takeOrder FormInput) 中的 FormInput 参数旨在绑定到表单。
当我注释掉时:
// if (FormInput != null)
// viewModel = FormInput;
然后代码按预期执行。但是我不明白为什么在我专门检查对象不为空时分配了null 对象。预期的行为是,如果已提交表单,则为 viewModel 分配已编辑的值,如果没有表单提交后,则 viewModel 使用默认值。最终,这些默认值将来自数据库。
为什么FormInput 为空时if (FormInput != null) 返回true?
【问题讨论】:
-
我不能更强烈地提倡你改变你的编码风格。它与驼峰式类名和大写参数名的标准风格完全相反。 (应该反过来)
-
就错误本身而言,您对每个参数进行了硬编码,但随后您继续使用
if (FormInput != null) viewModel = FormInput;覆盖该工作。大概FormInput不为null,但里面的所有属性都是null。这是回发的结果吗?为什么您希望FormInput拥有有效数据? -
@Kirk Woll - 我不知道有这样的约定。
-
@Kirk Woll - 感谢您提供资源!我得养成一些新习惯。
标签: c# asp.net-mvc asp.net-mvc-2