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

发布于 2024-09-03 09:55:19 字数 2916 浏览 1 评论 0原文

我在 ASP.MVC 中的 SelectList 方面遇到了一些麻烦。

问题是:我有一个 Create View 并开始了一个 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) 中终止。

感谢您抽出时间

乔治

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

度的依靠╰つ 2024-09-10 09:55:19

这应该从 改为

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

如果

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

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

(如果这是不正确或被否决的,请解释,因为我也渴望学习)

This should change from

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

to

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

If my limited understanding is correct, the problem lies with the parameter passed to the controller. You have create a view that accepts a DefinitionFormViewModel, however when you posting back to the server your current code expects a Definition.

(If this is incorrect or downvoted, please explain as I also am eager to learn)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文