我搜索了几个小时(或几天),但尚未找到解决方案。我想用正确的预选值编辑具有DropdownListFor的客户以进行称呼。MVC-3 DropdownList或DropdownListFor - 无法保存控制器POST中的值
我有3个实体(数据库第一个概念,这也不是我自己设计的...):客户,地址,称呼
一个客户有一个ADDRESS_ID(f_key)和地址已经得到了salutation_id (f_key)。例如,ADDRESS拥有姓氏和名字。在SALUTATION实体内部有一个sal1列,其中包含所有可能的称呼。
现在,我想通过一个视图模型看起来像这样修改我的客户:
public class CustomerViewModel
{
public CUSTOMER cust { get; set; }
public SelectList salutationList { get; set; }
CustomerRepository repository = new CustomerRepository();
public CustomerViewModel(int id)
{
cust = repository.GetCustomerByIdAsQueryable(id).Single();
salutationList = new SelectList(repository.GetSalutations(), cust.ADDRESS.SALUTATION.SAL1);
}
// Some more
}
的CutsomerRepository方法:
public class CustomerRepository
{
private MyEntities db = new MyEntities();
public IQueryable<CUSTOMER> GetCustomerByIdAsQueryable(int id) {...}
public IQueryable<CUSTOMER> GetCustomersByName(string firstName, string lastName, int maxCount) {...}
public List<string> GetSalutations()
{
var salutationList = new List<string>();
var salutationListQry = from s in db.SALUTATION
select s.SAL1;
salutationListTemp.AddRange(salutationListQry);
return salutationList;
}
// ...
}
这是我的控制器方法:
[HttpPost]
public ActionResult CustomerData(int id, FormCollection fc)
{
var vm = new CustomerViewModel(id);
// Why do I need the following line?
vm.cust = repository.GetCustomerByIdAsQueryable(id).Single();
try
{
UpdateModel(vm, fc);
repository.Save();
return View("CustomerData", vm);
}
catch (Exception e)
{
return View();
}
}
最后从我的部分看:
@model WebCRM.ViewModels.CustomerViewModel
@using (Html.BeginForm())
{
// ...
<div class="editor-label">
@Html.Label("Salutation:")
@Html.DropDownListFor(model => model.cust.ADDRESS.SALUTATION.SAL1, Model.salutationList)
// @Html.DropDownList("Salutation", Model.salutationList)
</div>
<div class="editor-label">
</div>
<div class="editor-field">
@Html.Label("Last name:")
@Html.EditorFor(model => model.cust.ADDRESS.LASTNAME)
@Html.ValidationMessageFor(model => model.cust.ADDRESS.LASTNAME)
</div>
<p>
<input type="submit" value="Speichern" />
</p>
}
更改和保存姓氏正常工作。但是,当保存salutation时,它会将SALUTATION实体中的SAL1值更改为我在DropdownListFor中选择的值。我想要的是改变我的客户在ADDRESS实体内部的salutation_id。为什么没有工作?
另一个奇怪的行为:当删除我的CustomerController中的标记行时,我甚至不能更改并保存姓氏。通常,CustimerViewModel的构造函数设置客户。那么为什么我必须拥有用于在ViewModel中设置客户的代码行?它是重复的,但必须在那里...
在此先感谢。
你怎么得什么类型的回“ObjectFactory.GetInstance()。的getCountries()”? –
Sleepwalker
谢谢,工作得很好!只是在那里检索实体,并没有ViewBag,但在我的ViewModel。 – Sleepwalker