开发者

asp.net mvc ajax EnableClientValidation and parse returned data

i use ajax.beginform with EnableClientValidation. problem -the form sends data to controller in any case even the form is not correct -what the proiblem?

the second qusion- i return ajax data like this

return Jso开发者_开发知识库n(new { value = "msg" });

how can i parse this data from javascript on view?


  1. Here's an extensive step by step tutorial explaining how to implement validation with ASP.NET MVC 2 and how to enable client validation. If you follow it correctly you should not have any problems.

  2. You could use the OnSuccess option:

    <% using (Ajax.BeginForm("SomeAction", new AjaxOptions {
        OnSuccess = "success"
    })) { %>
    

    where the success callback could look like this:

    <script type="text/javascript">
    function success(data) {
        alert(data.get_object());
    }
    </script>
    

UPDATE:

Here's a working example:

  • Model:

    public class Product
    {
        [Required]
        public string Name { get; set; }
    }
    
  • Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Product());
        }
        [HttpPost]
        public ActionResult Index(Product product)
        {
            return Json(new { status = "success" });
        }
    }
    
  • View:

    <script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script>
    <script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script>
    <script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcValidation.js") %>"></script>
    <script type="text/javascript">
    function success(data) {
        alert(data.get_object().status);
    }
    </script>
    
    <% Html.EnableClientValidation(); %>
    <% using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "success" })) { %>
        <%= Html.LabelFor(x => x.Name) %>
        <%= Html.TextBoxFor(x => x.Name) %>
        <%= Html.ValidationMessageFor(x => x.Name) %>
        <input type="submit" value="Create" />
    <% } %>
    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜