为什么我的模型没有被视图保存?

时间:2011-06-27 13:44:39

标签: c# asp.net-mvc

我一直在制作一些非常基本的MVC视图来保存一些数据。到目前为止,我已将它们全部基于LinqToSql类;现在我第一次将表单基于我自己创建的一个简单的小班,名为Purchase

public class Purchase {
  long UserID;
  decimal Amount;
  string Description;
}

创建了一个如下所示的视图:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestViewer.Models.Purchase>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
  Test Purchase
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
  <h2>
    Test Purchase</h2>
  <% using (Html.BeginForm("SavePurchase", "Home")) {%>
  <%: Html.ValidationSummary(true) %>
  <fieldset>
    <legend>Fields</legend>
    <div class="editor-label">
      <%: Html.LabelFor(model => model.UserID) %>
    </div>
    <div class="editor-field">
      <%: Html.DropDownListFor(model => model.UserID, 
    SystemUser.Select(u=>new SelectListItem{ Text=u.UserName, Value=u.ID.ToString()}).OrderBy(s=>s.Text))%>
      <%: Html.ValidationMessageFor(model => model.UserID) %>
    </div>
    <div class="editor-label">
      <%: Html.LabelFor(model => model.Amount) %>
    </div>
    <div class="editor-field">
      <%: Html.TextBoxFor(model => model.Amount) %>
      <%: Html.ValidationMessageFor(model => model.Amount) %>
    </div>
    <div class="editor-label">
      <%: Html.LabelFor(model => model.Description) %>
    </div>
    <div class="editor-field">
      <%: Html.TextBoxFor(model => model.Description) %>
      <%: Html.ValidationMessageFor(model => model.Description) %>
    </div>
    <p>
      <input type="submit" value="Create" />
    </p>
  </fieldset>
  <% } %>
  <div>
    <%: Html.ActionLink("Back to List", "Index") %>
  </div>
</asp:Content>

但是当我回到HomeController中的代码时:

public ActionResult SavePurchase(Purchase p) {
   // code here
}

对象p的所有字段值都有默认值(零和空格)。

为什么呢?我做错了什么?

1 个答案:

答案 0 :(得分:5)

Purchase课程中使用属性而不是字段(为了更好的封装),最重要的是,他们需要公共设置器才能实现此目的:

public class Purchase 
{
    public long UserID { get; set; }
    public decimal Amount { get; set; }
    public string Description { get; set; }
}

在您的示例中,您使用的是字段,但这些字段是内部,因此您不能指望默认模型绑定器能够为它们设置任何值,并且它们只是在POST操作中获取其默认值。

这就是说这些属性没有被说出的事实是你对这段代码的最小问题。在你的情况下,最糟糕的是你在你的视图中使用你的Linq2Sql模型,这是我看到人们在ASP.NET MVC应用程序中做的最糟糕的反模式之一。你绝对应该使用视图模型。这就是应该从控制器传递的视图,这是控制器应该从视图中获取的内容。