Persist SelectList in model on Post

前端 未结 2 1173
臣服心动
臣服心动 2020-12-11 17:13

In MVC4:

I have the following property in my model used for a dropdown list:

public SelectList Subjects { get; set; }

I set the Sub

2条回答
  •  春和景丽
    2020-12-11 17:45

    It is commonly accepted that you re-populate a SelectList after the Post action. Just extract it inside a method and call it in the Get and Post action.

    Posting it back again to the controller is not the way to go. You can cache the items in the SelectList so you won't have to make a query to the data store twice.

    Example:

    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)MemoryCache.Default.Get("SubjectList");
        }
        else
        {
            // The select list does not yet exists in the cache, fetch items from the data store.
            List selectList = _db.Subjects.ToList();
    
            // Cache the list in memory for 15 minutes.
            MemoryCache.Default.Add("SubjectList", selectList, DateTime.Now.AddMinutes(15));
            model.Subjects = selectList;
        }
    }
    

    Note: MemoryCache uses the System.Runtime.Caching namespace. See: System.Runtime.Caching namespace.

    Also, caching should be in a seperate layer between your controller (or business layer) and the data access layer, this is just for clarity.

提交回复
热议问题