What's best way to handle DropDownListFor in Asp.Net MVC 3?
i have this controller:
public ActionResult Novo()
{
var products = context.Product.Select(x => new SelectListItem
{
Text = x.Name,
Value = SqlFunctions.StringConvert((double)x.Id).Trim()
}).ToList();
MyViewModel myViewModel= new MyViewModel()
{
Products = products
};
return View(myViewModel);
}
[HttpPost]
public ActionResult Novo(MyViewModel myViewModel)
{
if (ModelState.IsValid)
{
...
context.SaveChanges();
return RedirectToAction("Index");
} else {
var products = context.Product.Select(x => new SelectListItem
{
Text = x.Name,
Value = SqlFunctions.StringConvert((double)x.Id).Trim()
}).ToList();
MyViewModel myViewModel= new MyViewModel()
{
Products = products
};
return View(myViewModel);
}
}
I must to populate Products in ViewModel in this two methods.
My ViewModel:
public class MyViewModel
{
public 开发者_运维知识库IEnumerable<SelectListItem> Products { get; set; }
public string ProductIdSelected { get; set; }
}
My HTML:
<div class="editor-field">
@Html.DropDownListFor(model => model.ProductIdSelected, Model.Products)
</div>
The problem is in my Controller, i must to populate ViewModel in this two methods. I don't like that, I don't like to create a method to populate ViewModel too because when validation fail, the others fields keeps populated, why my Products fields don't keeps populated too? I think using a method is ugly. Is there a way to avoid to use another method?
Is there a way to populate Producs in my ViewModel only once and cache the list of Products when someone do a Post and the Post is not valid.
If NOT, the better way is to use another method. Thanks.
What's wrong with creating a separate method to populate your VM (for the GET and for the POST
when validation fails)?
[HttpGet]
public ActionResult Novo()
{
MyViewModel myViewModel= new MyViewModel();
this.LoadProducts(myViewModel);
return View(myViewModel);
}
[HttpPost]
public ActionResult Novo(MyViewModel myViewModel)
{
if (ModelState.IsValid)
{
...
context.SaveChanges();
return RedirectToAction("Index");
}
else
{
MyViewModel myViewModel= new MyViewModel();
this.LoadProducts(myViewModel);
return View(myViewModel);
}
}
private void LoadProducts(MyViewModel model)
{
model.Products = context.Product.Select(x => new SelectListItem
{
Text = x.Name,
Value = SqlFunctions.StringConvert((double)x.Id).Trim()
}).ToList();
}
Additionally, you could provide another parameter for LoadProducts
so that it could set the selected item.
精彩评论