【发布时间】:2013-12-02 13:28:46
【问题描述】:
我尝试在控制器操作中在数据库中添加新实体。
这是我的模型课
public class Product
{
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter product model")]
public string Model { get; set; }
[Required(ErrorMessage = "Please enter product serial")]
public string Serial { get; set; }
[Required(ErrorMessage = "Please choose dealer")]
public int DealerID { get; set; }
[Required]
public Guid ClientID { get; set; }
[Required(ErrorMessage = "Please choose employee")]
public Guid EmployeeID { get; set; }
public virtual Dealer Dealer { get; set; }
public virtual Client Client { get; set; }
public virtual Employee Employee { get; set; }
[DisplayName("Commercial use")]
public bool UseType { get; set; }
}
这是在数据库中创建新产品的操作
public ViewResult Create()
{
PopulateDropDownLists();
var model = new Product();
return View(model);
}
[HttpPost]
public ActionResult Create(Product model)
{
try
{
if (ModelState.IsValid)
{
_repo.GetRepository<Product>().Add(model);
_repo.Save();
TempData["message"] = "Product was successfully created";
return RedirectToAction("List");
}
}
catch (DataException)
{
TempData["error"] =
"Unable to save changes. Try again, and if the problem persists, see your system administrator.";
return View("Error");
}
PopulateDropDownLists();
return View("Create");
}
CreateView 具有适当的模型类型(在这种情况下为产品类型)。代码如下
@using System.Web.Mvc.Html
@model STIHL.WebUI.Models.Product
@using (Html.BeginForm())
{
@Html.EditorFor(m => m.Name)
@Html.EditorFor(m => m.Model)
@Html.EditorFor(m => m.Serial)
<div class="form-group">
@Html.LabelFor(m => m.DealerID, "Dealer")
@Html.DropDownListFor(m => m.DealerID, new SelectList((IEnumerable)TempData["Dealers"],"DealerID", "DealerNumber"), string.Empty, new {@class = "form-control"})
@Html.ValidationMessageFor(m => m.DealerID, null, new {@class = "help-block"})
</div>
<div class="form-group">
@Html.LabelFor(m => m.EmployeeID, "Employee",new {@class = "control-label"})
@Html.DropDownListFor(m => m.EmployeeID, new SelectList((IEnumerable)TempData["Employees"],"EmployeeID", "FullName"),string.Empty, new {@class="form-control"})
@Html.ValidationMessageFor(m => m.EmployeeID, null, new {@class = "help-block"})
</div>
<div class ="ok-cancel-group">
<input class="btn btn-primary" type="submit" value="Create" />
@Html.ActionLink("Cancel", "List","Product",new {@class = "btn btn-primary"})
</div>
}
我总是在 [HttpPost] 操作中得到空引用而不是模型,但是如果我使用 ViewModel 而不是 Model 一切都很好(下面的 ViewModel 代码)
public class ProductViewModel
{
public Product Product { get; set; }
}
我认为它导致模型类具有虚拟属性,但无论如何我不明白为什么我使用 ViewModel 时可以。 谁能回答我? 提前谢谢。
【问题讨论】:
-
我觉得你也应该把视图放上去!!
-
如果从属性中删除“虚拟”会发生什么?
-
如果我删除虚拟属性,我可以使用模型类,没有 ViewModel 也可以
-
问题已编辑。我把查看代码放在那里
标签: c# asp.net-mvc entity-framework model asp.net-mvc-viewmodel