如果ModelState无效,我试图保持dropdownlist选择值
因为我想保留用户选择的数据,即使ModelState不是 有效
我的代码看起来像这样
获取方法:
[HttpGet]
public ActionResult Edit(int? Id)
{
using (var db = new NewsDatabaseEntities())
{
db.Configuration.LazyLoadingEnabled = false;
var Result = (from n in db.News.Include("Categories")
from c in db.Categories
where n.NewsId == Id
select new { news = n, neweCategories = n.Categories, cate = c }).ToList();
News NewsDetails = (from news in Result
select new News
{
NewsId = news.news.NewsId,
NewsTitle = news.news.NewsTitle,
NewsBody = news.news.NewsBody,
NewsImagePath = news.news.NewsImagePath,
Categories = news.neweCategories
}).FirstOrDefault();
var AllCategories = (from c in Result
select new Category
{
CategoryId = c.cate.CategoryId,
CategoryName = c.cate.CategoryName
}).ToList();
if (NewsDetails != null)
{
var model = new NewsViewModel();
model.NewsId = NewsDetails.NewsId;
model.AllCategories = AllCategories;
model.Categories = NewsDetails.Categories;
model.NewsTitle = NewsDetails.NewsTitle;
model.NewsBody = NewsDetails.NewsBody;
model.NewsImagePath = NewsDetails.NewsImagePath;
Session["AllCategories"] = new MultiSelectList(AllCategories, "CategoryId", "CategoryName", model.Categories.Select(J => J.CategoryId).ToArray());
Session["model"] = model;
return View(model);
}
else
{
return RedirectToAction("Index", "Home");
}
}
return View();
}
发布方法:
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(NewsViewModel model,FormCollection col)
{
if (!ModelState.IsValid)
{
model = (NewsViewModel)Session["model"];
return View(model);
}
查看:
@Html.DropDownListFor(c => c.SelectedCategoriesIds, (MultiSelectList)Session["AllCategories"], new { id = "DropDownList1", multiple = "multiple", @class = "form-control" })
答案 0 :(得分:2)
因为您正在使用您在GET操作中设置的会话数据覆盖视图模型对象(具有所选选项值)。
您应该将选定的选项值读取到临时变量并使用它。
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(NewsViewModel model,FormCollection col)
{
if (!ModelState.IsValid)
{
var selected= model.SelectedCategoriesIds;
model = (NewsViewModel)Session["model"];
model.SelectedCategoriesIds =selected;
return View(model);
}
//save and return something**strong text**
}
更好的解决方案不是在这里使用会话。您可以从db表/缓存中再次读取值。同样,为了呈现下拉列表,您可以简单地向视图模型添加属性并使用它。
public class NewsViewModel
{
public List<SelectListItem> AllCategories {set;get;}
//Other properties
}
并且在您的GET操作中,不是将类别设置为Session,而是将其设置为此属性
public ActionResult Edit(int? id)
{
var vm = new NewsViewModel();
vm.AllCategories = GetCategories();
return View(vm);
}
private IEnumerable<SelectListItem> GetCategories()
{
return db.Categories
.Select(s=>new SelectListItem { Value=s.Id.ToString(),
Text=s.Name).ToList();
}
并在您的视图中
@model NewsViewModel
@using(Html.BeginForm())
{
<label> Select items <label>
@Html.ListBoxFor(s=>s.SelectedCategoriesIds,AllCategories )
<input type="submit" />
}
现在在您的HttpPost操作中,当模型验证失败时,您不需要使用会话,只需调用相同的方法来重新加载AllCategories
属性。
if (!ModelState.IsValid)
{
model.AllCategories=GetCategories();
return View(model);
}