Model.IsValid总是返回true

时间:2011-05-19 19:30:01

标签: validation asp.net-mvc-3 ninject-2

好的我在这附近的智慧结束了。我有一个带有viewmodel的简单MVC3应用程序

视图模型

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

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

控制器

    [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 的形式出现。即使名称留空。这就像模型/ viewmodel根本没有验证。这适用于其他应用程序,所以我很确定我没有挂钩。我已经包含了所有验证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工具更新之前运作良好。

4 个答案:

答案 0 :(得分:3)

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

Ninject - Setting up an MVC3 application

答案 1 :(得分:1)

您是否正在使用其他默认模型装订器(使用DI)?我很确定默认模型绑定器将在绑定时验证对象。如果您没有使用默认值,则可能不会遇到相同的行为。

答案 2 :(得分:0)

尝试使用

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

这应该正确应用data-属性

答案 3 :(得分:0)

我使用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;
}
相关问题