【问题标题】:MVC: Selected values in a listbox when the user is on the edit pageMVC:当用户在编辑页面上时列表框中的选定值
【发布时间】:2012-03-19 08:09:38
【问题描述】:

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

当用户创建一个问题时,他/她可以从一个 ListBox 中选择多个 CoreValues。 当用户转到编辑页面以更改问题上的 CoreValues 时,我希望列表框已经选择了那些 corevalues,我知道如何做到这一点吗?

这是我的视图模型:

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>

提前致谢!

【问题讨论】:

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


【解决方案1】:

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

签名看起来像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多