1
我有一個表單,裏面有一個局部視圖來呈現多個子控件。獲取從部分視圖發送的值
主視圖:
@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>
}
PROFIL控制器(用於局部視圖):
[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
您需要將該列表添加爲視圖模型的屬性,包括可能值列表和所選值列表,然後查看第二個答案:http://stackoverflow.com/questions/4872192/ CheckBoxList的功能於mvc3-0 – glenatron