MVC:当用户在编辑页面上时,列表框中的选定值

时间:2012-03-19 08:09:38

标签: asp.net-mvc asp.net-mvc-3 entity-framework selectedvalue

我首先在我的项目中使用MVC3 EF模型。

当用户创建问题时,他/她可以从ListBox中选择多个CoreValues。 当用户进入编辑页面以更改问题上的CoreValues时,我希望列表框中已经选择了那些核心值的任何关于我如何做到这一点的想法?

这是我的ViewModel:

public class AdminEditViewModel
{
    public string QuestionText { get; set; }
    public string SubjecTypeName { get; set; }
    public string CoreValueName { get; set; }
    public SelectList SubjectTypes { get; set; }
    public IEnumerable<string> SelectedValuesOfCoreValues { get; set; }
    public IEnumerable<CoreValue> CoreValues { get; set; }
}

这是我控制器中的GET和POST操作:

public ActionResult Edit(int id)
{
            Question question = AdminRep.GetQuestionById(id);
            AdminEditViewModel model = new AdminEditViewModel();
            List<SubjectType> subjectypes = AdminRep.GetAllSubjectTypesById();
            model.CoreValues = AdminRep.GetAllCorevaluesById();
            model.QuestionText = question.QuestionText;
            model.SubjectTypes = new SelectList(subjectypes, "Id", "Name",question.SubjectType.First().Id);


            return View(model);
}

        //
        // POST: /Admin/Edit/5

[HttpPost, ActionName("Edit")]
public ActionResult EditConfirmed(int id, AdminEditViewModel model)
{

            if (ModelState.IsValid)
            {
                Question question = AdminRep.GetQuestionById(id);
                question.QuestionText = model.QuestionText;
                question.SubjectType.Clear();
                question.CoreValue.Clear();
                foreach (var item in model.SelectedValuesOfCoreValues)
                {
                    var CoreValueID = int.Parse(item);
                    var GetAllCoreValuesID = AdminRep.GetByCoreValueID(CoreValueID);
                    question.CoreValue.Add(GetAllCoreValuesID);

                }
                var SubjectTypeID = int.Parse(model.SubjecTypeName);
                var getallS = AdminRep.GetBySubjectTypeID(SubjectTypeID);
                question.SubjectType.Add(getallS);
                AdminRep.save();
                return RedirectToAction("Index");
            }    
             return View(model);
}

和我的观点:

<div class="editor-field">
    @Html.ListBoxFor(m => m.SelectedValuesOfCoreValues, new MultiSelectList(Model.CoreValues, "Id", "Name"), new { @class = "selectstyle" })
    @Html.ValidationMessageFor(model => model.CoreValueName)
</div>

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以让您的action方法接受FormCollection作为参数。然后,您可以编写自己的逻辑,从该对象中提取所需的任何数据。基本上,FormCollection将包含作为键值对发布的表单内的所有字段。

签名看起来像这样:

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(FormCollection form) {   // logic here to  }