Hello guys. I'm having some troubles with SelectList in ASP.MVC.
Here is the issue: I have a Create View and begind a ViewModel model.
The page load just fine (GET verb). But when posting, something happens, and my model is considered invalid, and it cannot insert. Here's what i've tried so far.
public class DefinitionFormViewModel
{
private Repository<Category> categoryRepository = new Repository<Category>();
public Definition ViewDefinition { get; private set; }
public SelectList Categories { get; private set; }
public DefinitionFormViewModel(Definition def)
{
ViewDefinition = def;
// here i wanted to place it directly, like shown in NerdDinner Tutorial
// new SelectList(categoryRepository.All(),ViewDefinition.Category);
Categories = new SelectList(categoryRepository.All(), "CategoryId", "CategoryName", ViewDefinition.CategoryId);
}
}
// pageview which inherits DefinitionFormViewModel
<div class=editor-field">
<%= Html.DropDownList("Category",Model.Categories) %>
<%= Html.ValidationMessageFor(model => Model.ViewDefinition.Category) %>
</div>
// controller methods
[Authorize]
public ActionResult Create()
{
Definition definition = new Definition();
return View(new DefinitionFormViewModel(definition));
}
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult Create(int id,Definition definition)
{
Term term = termRepository.SingleOrDefault(t => t.TermId == id);
if (term == null)
{
return View("NotFound", new NotFoundModel("Termo não encontrado", "Termo não encontrado",
"Nos desculpe, mas não conseguimos encontrar o termo solicitado.", "Indíce de Termos", "Index", "Term"));
}
else
{
if (ModelState.IsValid)
{
try
{
definition.TermId = term.TermId;
definition.ResponsibleUser = User.Identity.Name;
UpdateModel(definition);
term.Definitions.Add(definition);
termRepository.SaveAll();
return RedirectToAction("Details", "Term", new { id = term.TermId });
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
ModelState.AddModelError("DatabaseError", "Houve um erro na inserção desta nova definição");
}
catch
{
foreach (RuleViolation rv in definition.GetRuleViolations())
{
ModelState.AddModelError(rv.PropertyName, rv.ErrorMessage);
}
}
}
}
return View(new DefinitionFormViewModel(definition));
}
I'm sorry about the long post, but I cant figure this out. I got no graphic errors or exceptions. My execution terminates in if (ModelState.IsValid).
Thanks for your time
George