Asp-mvc中的SelectList和数据库中的数据

时间:2010-05-26 18:18:09

标签: asp.net-mvc-2 selectlist

我在ASP.MVC中遇到了一些问题。

问题在于:我有一个创建视图并生成一个ViewModel模型。

页面加载很好(GET动词)。但是在发布时,会发生一些事情,我的模型被视为无效,并且无法插入。这是我到目前为止所尝试的内容。

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

我对这篇长篇文章感到抱歉,但我无法弄清楚这一点。我没有图形错误或异常。我的执行终止于if(ModelState.IsValid)。

感谢您的时间

乔治

1 个答案:

答案 0 :(得分:0)

这应该从

改变
[AcceptVerbs(HttpVerbs.Post), Authorize]
    public ActionResult Create(int id,Definition definition)
    {...}

 [AcceptVerbs(HttpVerbs.Post), Authorize]
        public ActionResult Create(int id,DefinitionFormViewModel definition)
        {...}

如果我的理解有限,问题在于传递给控制器​​的参数。您已经创建了一个接受DefinitionFormViewModel的视图,但是当您回发到服务器时,您当前的代码需要Definition

(如果这不正确或被投票,请解释,因为我也渴望学习)