我已经建立了我的实体通过数据库-首先,因为我必须使用一个现有的数据库。
现在,假设我有实体客户和国家,我想编辑客户。我的观点应该包含一些东西,如名字,姓氏和国家,这是一个DropdownList来自所有国家的实体。为此,我创建了一个使用这两个实体的CustomerViewModel。但我不知道这一切是否都是正确的,因为有些事情是行不通的。
首先是我的CustomerViewModel的代码:
public class CustomerViewModel
{
public CUSTOMER customer { get; set; }
public COUNTRY country { get; set; }
public IEnumerable<SelectListItem> countryList { get; set; }
MyEFEntities db = new MyEFEntities();
public CustomerViewModel(int id)
{
IEnumerable<CUSTOMER> customerList = from c in db.CUSTOMER
where c.CUSTOMERNO== id
select c;
customer = customerList.First();
var countryListTemp = new List<String>();
var countryListQry = from s in db.COUNTRY
select s.COUNTRY_ABBREVIATION;
countryListTemp.AddRange(countryListQry);
countryList = new SelectList(countryListTemp);
}
}然后CustomerController.cs:
public ViewResult CustomerData(int id = 0)
{
// if (id == 0) { ... }
var viewModel = new CustomerViewModel(id);
return View(viewModel);
}
[HttpPost]
public ActionResult CustomerData(CustomerViewModel model)
{
db.Entry(model.customer).State = System.Data.EntityState.Modified;
db.SaveChanges();
return View(model);
}最后但并非最不重要的是CustomerData.cshtml:
@model MyApp.ViewModels.CustomerViewModel
@{
ViewBag.Title = "Customer";
}
<h2>
Customer</h2>
@using (Html.BeginForm("CustomerData", "Customer"))
{
@Html.ValidationSummary(true)
<div id="tabs">
<ul>
<li><a href="#data">Data</a></li>
<li><a href="#hobbies">Hobbies</a></li>
<li><a href="#stuff">Stuff</a></li>
</ul>
<div id="data">
<div class="editor-label">
@Html.Encode("Country:")
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.country.COUNTRY_ABBREVIATION, Model.countryList, Model.customer.ADDRESS.COUNTRY.COUNTRY_ABBREVIATION)
</div>
<div class="editor-label">
@Html.Encode("Last name:")
@Html.TextBox("lastName", @Model.customer.ADDRESS.NAME)
</div>
<div class="editor-label">
@Html.Encode("First Name:")
@Html.TextBox("firstName", @Model.customer.ADDRESS.FIRSTNAME)
</div>
</div>
<div id="hobbies">
<p>
Hobbies
</p>
</div>
<div id="stuff">
<p>
Stuff
</p>
</div>
</div>
<p>
<input type="submit" value="Save" />
</p>
}观看效果很好。我到了http://localhost:12345/Customer/CustomerData/4711网址,可以看到该客户的当前值。
现在我漏掉了一些东西。
发布于 2011-11-28 12:05:52
恐怕这个设计不好。永远不要从模型中进行DB访问,这就是Controller的目的。模型应该只保存Controller提供给它的数据。
如果从模型中筛选出DB访问或任何类型的逻辑,您会发现系统的设置和维护变得更加容易,甚至可能解决您提到的问题。
https://stackoverflow.com/questions/8295447
复制相似问题