私はいくつかの子コントロールをレンダリングするために、内部に部分的なビューを持つフォームを持っています。部分ビューから送信された値を取得する
メインビュー:(部分図用)
@model Test_mvc.Models.Entity.Question
@{
ViewBag.Title = "Edit";
Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
@*snip*@
<fieldset>
<legend>Profils</legend>
@Html.Action("CheckboxList", "Profil", new { id_question = Model.id })
</fieldset>
<p>
<input type="submit" value="Enregistrer" />
</p>
}
プロフィールコントローラ:
[ChildActionOnly]
public ActionResult CheckboxList(int id_question)
{
var profils = db.Profil.Include("Profil_Question")
.OrderBy(p => p.nom).ToList();
ViewBag.id_question = id_question;
return PartialView(profils);
}
Profil.CheckBoxListビュー:
@model List<Test_mvc.Models.Entity.Profil>
@foreach (var p in Model)
{
<input type="checkbox" name="[email protected](p.id)"
@if (p.Profil_Question.Where(pc => pc.id_question == ViewBag.id_question).Any())
{
@:checked="checked"
} />
@Html.Label("profil_" + p.id, p.nom)
<br />
}
(私が使用したくありません@ Html.CheckBoxなぜなら、チェックボックスがオンになっていると "true、false"が送信されたくないからです)。
今日、私がチェックされたチェックボックス、私はこれを行うを取得したいが、私はそれはひどいだと思う場合:(メインビュー用)
質問コントローラ:
[HttpPost]
public ActionResult Edit(Question question)
{
if (ModelState.IsValid)
{
db.Question.Attach(question);
db.ObjectStateManager.ChangeObjectState(question, EntityState.Modified);
db.SaveChanges();
// this is what I want to change :
foreach (string r in Request.Form)
{
if (r.StartsWith("profil_") && (Request.Form[r] == "true" || Request.Form[r] == "on")) {
var p_q = new Models.Entity.Profil_Question();
p_q.id_profil = int.Parse(r.Replace("profil_", ""));
p_q.id_question = question.id;
db.AddToProfil_Question(p_q);
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(question);
}
どうでしょう最後のコードセクションで "foreach"を置き換えますか?
おかげ
これはちょっといいですが、依然としてRequest.Formを使用する必要がありますか? ViewModelを使用してパーシャルビューの値をコントローラに「バインド」するにはどうすればよいですか? – thomasb
そのリストをviewmodelの属性として追加する必要があります。可能な値のリストと選択した値のリストの両方を入力してから、ここで2番目の答えを見てください。http://stackoverflow.com/questions/4872192/ checkboxlist-in-mvc3-0 – glenatron