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="profil_@(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”?

谢谢

4

1 回答 1

1

我会尝试的第一件事是给我的所有复选框赋予相同的名称,并将@id 作为框的值:

@foreach (var p in Model) {     
     <input type="checkbox" name="profil_checkbox" value="@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 /> } 

然后,与其搜索,profil_@id我应该得到一组profile_checkbox更容易使用的结果。我不记得 MVC3 是如何处理这个的,所以我不能保证你会在回发中得到什么,但这应该很容易在调试期间检查。

于 2012-05-10T13:46:30.317 回答