views:

292

answers:

1

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 Json(new { value = "msg" });

how can i parse this data from javascript on view?

A: 
  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" />
    <% } %>
    
Darin Dimitrov
i read this article, i do it like hi describe, but it work only for html.beginborm, but when i use ajax.beginform- post data go to controller even if clienc validation shows errors
kusanagi
Please see my update illustrating a working example of client validation with `Ajax.BeginForm`.
Darin Dimitrov
nope, here desision, may be you interested. article http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx but solution in comments second comment from end
kusanagi