7

在 MVC4 中:

我的模型中有以下属性用于下拉列表:

public SelectList Subjects { get; set; }

我在页面加载时的 Index() Action 中设置 Subjects 属性并返回模型。

使用 SelectListItems 可以很好地填充下拉列表。

@Html.DropDownListFor(x => x.Subject, new SelectList(Model.Subjects, "Text", "Text", "Other"))

当我提交表单时,模型中的 Subjects SelectList 已更改为 null。必须有一种简单的方法来将其保留在 HttpPost 上。我假设我也想提交和发布这个 SelectList 以及所有表单字段?我该怎么做?

4

2 回答 2

7

通常认为您SelectList在操作后重新填充 a Post。只需在方法中提取它并在GetandPost操作中调用它。

将其再次发布回控制器不是要走的路。您可以缓存 SelectList 中的项目,这样您就不必对数据存储进行两次查询。

例子:

public ActionResult Create()
{
    var model = new SubjectModel();
    PopulateSubjectList(model);
    return View(model);
}

[HttpPost]
public ActionResult Create(SubjectModel model)
{
    if (ModelState.IsValid)
    {
        // Save item..
    }
    // Something went wrong.
    PopulateSubjectList(model);
    return View(model);
}

private void PopulateSubjectList(SubjectModel model)
{
    if (MemoryCache.Default.Contains("SubjectList"))
    {
        // The SubjectList already exists in the cache,
        model.Subjects = (List<Subject>)MemoryCache.Default.Get("SubjectList");
    }
    else
    {
        // The select list does not yet exists in the cache, fetch items from the data store.
        List<Subject> selectList = _db.Subjects.ToList();

        // Cache the list in memory for 15 minutes.
        MemoryCache.Default.Add("SubjectList", selectList, DateTime.Now.AddMinutes(15));
        model.Subjects = selectList;
    }
}

注意:MemoryCache使用System.Runtime.Caching命名空间。请参阅:System.Runtime.Caching 命名空间

此外,缓存应该位于控制器(或业务层)和数据访问层之间的单独层中,这只是为了清楚起见。

于 2013-09-09T17:56:39.450 回答
2

浏览器只回发表单元素上的选定值。此外,回发可以从数据存储中检索到的值也不是一个好主意。您必须像在填充列表时一样提取列表中的项目。

此外,MVC 不像 .NET 网页那样维护页面的状态,因为它没有视图状态。开发人员全权负责管理回发之间的页面状态,这是 MVC 设计模式的精髓。

于 2013-09-09T17:52:28.857 回答