Iは数時間(または数日)検索し、解決策をまだ見つけられませんでした。私は適切なあらかじめ選択された値で挨拶のためにDropdownListForで顧客を編集したい。MVC-3 DropdownListまたはDropdownListFor - コントローラーPOSTの値を保存できません。
私は3つのエンティティ(データベース最初のコンセプト、これは私自身のデザインではありませんが...)持っている:顧客、住所、挨拶
お客様がADDRESS_ID(f_key)を有し、ADDRESSがsalutation_idを持っています(f_key)。 ADDRESSには例として姓と名が入っています。 SALUTATIONエンティティの内部には、すべての可能な挨拶を保持する列sal1があります。
さて、私はこのようになりますViewModelに介して、私の顧客を編集する:
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エンティティのSAL1値がDropdownListForで選択した値に変更されます。私が望むのは、私の顧客のADDRESSエンティティ内のsalutation_idを変更することです。なぜそれは働いていないのですか?
もう1つ奇妙な振る舞い:CustomerControllerでマークされた行を削除すると、姓を変更して保存することさえできません。通常、CustimerViewModelのコンストラクタが顧客を設定します。では、ViewModel内で顧客を設定するための一連のコードを用意する必要があるのはなぜですか?重複していますが、そこにある必要があります。
ありがとうございます。
どのようなタイプのあなたが戻ってから入手できますか"ObjectFactory.GetInstance()。GetCountries()"? –
Sleepwalker
ありがとう、うまくいった!そこにあるエンティティを取得し、ViewBagなしで、ViewModel内で実行しました。 – Sleepwalker