Model.IsValid always returning true

﹥>﹥吖頭↗ 提交于 2019-12-10 17:45:10

问题


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.


回答1:


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




回答2:


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.




回答3:


Try using

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

That should apply the data- attributes correctly




回答4:


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


来源:https://stackoverflow.com/questions/6063893/model-isvalid-always-returning-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!