开发者

Asp.net Mvc2 Data Annotations Validation (Client Side works, Server side Doesnt??)

开发者 https://www.devze.com 2023-01-11 03:30 出处:网络
I\'m using an entity model with metadata annotations.My controller me开发者_运维知识库thod looks like this...

I'm using an entity model with metadata annotations. My controller me开发者_运维知识库thod looks like this...

        if (!ModelState.IsValid)
        {
            return View(model);
        }
        else
        {
            UpdateModel(model);
            repo.Save();
            return RedirectToAction("Index");
        }

If I enable client side validation in the view I'll get the error per the Attributes from the metadata class. If I take clientside validation out, error gets thrown from saving to the DB rather than return the view with an Error Summary.

This is the top portion of my view....

<% using (Html.BeginForm())
   {%>
<%: Html.ValidationSummary(true) %>

I've tried running without debugging (ctrl + f5) in debug and release mode as well as setting breakpoints and Debugging (f5) but it just seems weird to get Client side validation without server side validation. What am I missing here?


UpdateModel populates the model from form collection, routing parameters, etc. and does validation on the server side. You need to check ModelState.IsValid after updating. The usual pattern is...

if (!TryUpdateModel(model))
{
  // Validation Failed...
  return View(model);
}

// Validation Passed...

Note that TryUpdateModel catches exceptions and returns false if they're raised. If they aren't, then it simple returns ModelState.IsValid.

0

精彩评论

暂无评论...
验证码 换一张
取 消