Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c# - Persist SelectList in model on Post

In MVC4:

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

public SelectList Subjects { get; set; }

I set the Subjects property in my Index() Action on page load and return the model.

The dropdown gets populated just fine with the SelectListItems.

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

When I submit the form the Subjects SelectList in the model has changed to null. There has to be a simple way to persist this on HttpPost. I assume I want to submit and post this SelectList as well, along with all the form fields? How would I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<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;
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...