Model.IsValid 始终返回 true

发布于 2024-11-09 01:08:49 字数 2721 浏览 5 评论 0原文

好吧,我已经束手无策了。我有一个简单的 MVC3 应用程序,带有视图模型

ViewModel

    public class TicketViewModel {
    public Ticket Ticket { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Requestor's name is required.")]
    public string Name { get; set; } }

Controller

    [HttpPost]
    public ActionResult Create(TicketViewModel vm)
    {
        if(ModelState.IsValid) {

            TempData["message"] = "Your ticket has been submitted.";
            TempData["message-class"] = "success";

            return RedirectToAction("Index");
        }

        TempData["message-class"] = "error";

        return View("Index", vm);
    }

出于某种原因,ModelState.IsValid 始终显示为 true 。即使名称留空。就像模型/视图模型根本没有验证一样。这适用于其他应用程序,所以我很确定我没有连接某些东西。我已经包含了所有验证 javascript,但我认为这不是现在的问题。

更新 有趣的是,由 @Html.TextBoxFor() 生成的 html 标签不包含 data-val 和 data-val-required 属性。

查看

@model MyApp.ViewModels.TicketViewModel

@{
    ViewBag.Title = "Tickets";
}

<div id="main-content">
    <section class="large">
      <div class="section">
        <div class="section-header">Submit Ticket</div>
        <div class="section-content">
          <div class="message"></div>

          @using( Html.BeginForm("Create", "Home", FormMethod.Post) ) {
            <h2>User Information</h2>
            <dl>
              <dt>@Html.LabelFor( m => m.Name)</dt>
              <dd>
                @Html.TextBoxFor( m => m.Name)
                @Html.ValidationMessageFor( m => m.Name)
              </dd>

              <dt></dt>
              <dd><button>Submit</button></dd>
            </dl>
          }
        </div>
      </div>
    </section>
</div>

更新 II

现在这很有趣。我创建了一个新的应用程序并使用基本代码进行工作。然后,当我将 DI 代码添加到 global.asax.cs 时,验证停止工作。具体来说,当我添加

    public void SetupDependencyInjection() {
        _kernel = new StandardKernel();
        RegisterServices(_kernel);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(_kernel));
    }

并从 Application_Start() 调用它时,

    protected void Application_Start()
    {
        SetupDependencyInjection();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

如果我删除 SetupDependencyInjection() 验证就会开始工作。需要明确的是,DI 效果很好,但它似乎会扼杀验证。这在 MVC3 工具更新之前运行良好。

Ok I am near wits end here. I've got a simple MVC3 application with a viewmodel

ViewModel

    public class TicketViewModel {
    public Ticket Ticket { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Requestor's name is required.")]
    public string Name { get; set; } }

Controller

    [HttpPost]
    public ActionResult Create(TicketViewModel vm)
    {
        if(ModelState.IsValid) {

            TempData["message"] = "Your ticket has been submitted.";
            TempData["message-class"] = "success";

            return RedirectToAction("Index");
        }

        TempData["message-class"] = "error";

        return View("Index", vm);
    }

For some reason ModelState.IsValid is coming through as true all the time. Even when Name is left blank. It's like the model/viewmodel isn't validating at all. This works on other applications so I'm pretty sure I'm not hooking up something. I've got all the validation javascript included as well though I don't think that's the problem right now.

Update
Interestingly enough, the html tags that are being generated by @Html.TextBoxFor() are NOT including the data-val and data-val-required attributes.

View

@model MyApp.ViewModels.TicketViewModel

@{
    ViewBag.Title = "Tickets";
}

<div id="main-content">
    <section class="large">
      <div class="section">
        <div class="section-header">Submit Ticket</div>
        <div class="section-content">
          <div class="message"></div>

          @using( Html.BeginForm("Create", "Home", FormMethod.Post) ) {
            <h2>User Information</h2>
            <dl>
              <dt>@Html.LabelFor( m => m.Name)</dt>
              <dd>
                @Html.TextBoxFor( m => m.Name)
                @Html.ValidationMessageFor( m => m.Name)
              </dd>

              <dt></dt>
              <dd><button>Submit</button></dd>
            </dl>
          }
        </div>
      </div>
    </section>
</div>

UPDATE II

Well now this is interesting. I created a fresh app and got things working with basic code. Then when I added DI code to the global.asax.cs validations stopped working. Specifically, when I add

    public void SetupDependencyInjection() {
        _kernel = new StandardKernel();
        RegisterServices(_kernel);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(_kernel));
    }

and call it from Application_Start()

    protected void Application_Start()
    {
        SetupDependencyInjection();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

if I remove SetupDependencyInjection() validations start working. To be clear, DI works well but it seems to kill validations. This worked well prior to MVC3 Tools Update.

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

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

发布评论

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

评论(4

┼── 2024-11-16 01:08:49

我找到了解决方案。似乎当你通过 nuget 安装 Ninject 时,配置有点不同。它从 App_Start 文件夹配置您的应用程序。基本上,我正在加倍使用从 global.asax 调用的 Ninject-Fu。尽管应用程序的其他部分正在工作,但这最终导致了奇怪的验证问题。

Ninject - 设置 MVC3 应用程序

I was able to find a solution. Seems that when you install Ninject via nuget the configuration is a little different. It configures your application from the App_Start folder. Basically I was doubling up on my Ninject-Fu calling in from global.asax. This ended up causing the weird validation issues, though the other parts of the application were working.

Ninject - Setting up an MVC3 application

深爱不及久伴 2024-11-16 01:08:49

您是否可能使用默认模型绑定器(带有 DI)以外的其他东西?我非常确定默认模型绑定器将在绑定时验证对象。如果您不使用默认的,您可能不会遇到相同的行为。

Are you perhaps using something other that the default model binder (with the DI)? I'm pretty sure that the default model binder will validate an object upon binding. If you are not using the default one, you may not experience the same behavior.

街角迷惘 2024-11-16 01:08:49

尝试使用

@Html.EditorFor(model => model.Name)

应该正确应用 data- 属性

Try using

@Html.EditorFor(model => model.Name)

That should apply the data- attributes correctly

梦回梦里 2024-11-16 01:08:49

我将 Ninject.Mvc 与 DependencyResolver 一起使用时遇到了同样的错误。原因是我为每个 Bootstrapper 和 DependencyResolver 对象创建了一个新的 IKernel 实例。

//Application_Start()
DependencyResolver.SetResolver(new NinjectDependencyResolver(NinjectBooster.CreateKernel()));

为了解决这个问题,我更改了代码以使用相同的缓存实例,如下所示:

//Application_Start()
DependencyResolver.SetResolver(new NinjectDependencyResolver(NinjectBooster.GetKernel()));
...

//NinjectMVC.cs
private static IKernel _kernel;

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
public static IKernel GetKernel()
{
   if (null == _kernel)
   {
       _kernel = new StandardKernel();
       RegisterServices(_kernel);
   }
        return _kernel;
}

I got the same error using Ninject.Mvc together with DependencyResolver. The reason was that I created a new IKernel instance for each Bootstrapper and DependencyResolver object.

//Application_Start()
DependencyResolver.SetResolver(new NinjectDependencyResolver(NinjectBooster.CreateKernel()));

To solve the problem I've changed the code to use the same cached instance, like this:

//Application_Start()
DependencyResolver.SetResolver(new NinjectDependencyResolver(NinjectBooster.GetKernel()));
...

//NinjectMVC.cs
private static IKernel _kernel;

/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
public static IKernel GetKernel()
{
   if (null == _kernel)
   {
       _kernel = new StandardKernel();
       RegisterServices(_kernel);
   }
        return _kernel;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文