我已经通过数据库优先建立了我的实体,因为我必须使用现有的数据库。ASP.Net-MVC-3 ViewModel的初学者问题并将它们提交给控制器
现在,假设我有实体客户和国家,我想编辑客户。 我的视图应该包含名字,姓氏和国家,这是来自实体中所有国家/地区的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>
}
查看作品大。我访问URL http://localhost:12345/Customer/CustomerData/4711,可以看到该客户的当前值。
现在,我错过了一些东西。
保存按钮不起作用。如果我点击它,我收到一条错误信息,发现这个对象没有无参数的构造函数。但我想将ViewModel传递回控制器。如何重载Html.BeginForm()方法?
如何存储客户更改的值?是通过编辑文本字段来完成,还是必须使用Html.TextboxFor()而不是Html.Textbox?这对初学者来说太复杂了。我根本没有进入LINQ风格。
Dropdownlist不能正常工作。客户已经有两次了。看起来,第三个参数不预先标记一个项目,而是添加一个默认项目。 Html.Dropdownlist会更好吗?
谢谢,我也想过这个。 Google是我的朋友。你能否提供一些更多的信息? – Sleepwalker
当您的模型由您的控制器填充的属性组成时,您可以使用@ Html.EditorFor将文本框等绑定到这些属性,如@ Html.EditorFor(m => m.SomeProperty)。 –
ViewModel中是否应该有一个空的构造函数?我应该在其中使用IEnumerable国家吗?我有点卡住了,因为这对我来说都是新的。 –
Sleepwalker