ненатрапчиво валидиране на динамично добавен частичен изглед в Ajax.BeginForm (не работи)

Използвам MVC 2 с aspx view engine.

В един частичен изглед отварям един модален изскачащ прозорец с "bootstrap-modal.js".

В тази клиентска валидация не работи.

Когато изобразявам изгледа си като "‹% Html.RenderPartial("Myview"); %> " и ‹% Html.RenderAction("Myview"); %> , проверката от страна на клиента работи добре. Но не работи, когато динамично зареждам моя частичен изглед с jquery.

Прочетох следните дискусии и кандидатствах според ръководството в тях, но без успех.

https://stackoverflow.com/a/9324173/1752787

Ненатрапчивото валидиране не работи с Ajax.BeginForm

http://forums.asp.net/t/1716864.aspx/1

Коя е малката ми грешка?

Моят основен изглед:

 <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
 </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<link href="/bg../../Content/BoroTheame/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="/bg../../Content/BoroTheame/bootstrap-responsive.min.css" rel="stylesheet"
    type="text/css" />
<link href="/bg../../Content/BoroTheame/colorbox.css" rel="stylesheet" type="text/css" />
<link href="/bg../../Content/BoroTheame/fullcalendar_beoro.css" rel="stylesheet" type="text/css" />
<link href="/bg../../Content/BoroTheame/beoro.css" rel="stylesheet" type="text/css" />
<link href="/bg../../Content/BoroTheame/datatables_beoro.css" rel="stylesheet" type="text/css" />
<link href="/bg../../Content/BoroTheame/TableTools.css" rel="stylesheet" type="text/css" />
<link href="/bg../../Content/BoroTheame/ModelPopupcss.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/modernizr-2.6.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-migrate-1.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/bootstrap.min.js" type="text/javascript"></script>
<script src="../../Scripts/bootstrap-modal.js" type="text/javascript"></script>
<script src="../../Scripts/bootstrap-modalmanager.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.debug.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
<%--<script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>--%>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    function loadPartialViewForManageUser() {

        // alert('ajax..');



        $.ajax({
            type: "POST",
            cache: false,

            url: 'Home/test',
            success: function (html) {

                $("#divContactInfo").html(html);
                $.validator.unobtrusive.parse($("#divContactInfo"));
                //                    var form = $("#divContactInfo").closest("form");
                //                    form.removeData('validator');
                //                    form.removeData('unobtrusiveValidation');

                //                    $.validator.unobtrusive.parse(form);
            },
            error: function (e, args) {

            }
        });
        return false;

    }

</script>
<h2>
    <%: ViewData["Message"] %></h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">
        http://asp.net/mvc</a>.
</p>
<!-- Button to trigger modal -->
<a href="/bg#myModal" role="button" class="btn" data-toggle="modal" onclick="return loadPartialViewForManageUser();">
    Launch demo modal</a>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
    aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×</button>
        <h3 id="myModalLabel">
            Modal header</h3>
    </div>
    <div class="modal-body">
        <p>
            One fine body…</p>
        <%--  <% Html.RenderPartial("test"); %>--%>
        <div id="divContactInfo">
            <%--<% Html.RenderAction("test"); %>--%>
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">
            Close</button>
        <button class="btn btn-primary">
            Save changes</button>
    </div>
</div>

My Partial view :

   <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DataAnnotation.Models.TestDA>" %>


   <script type="text/javascript">
//    $.validator.unobtrusive.parse("form");
// $.validator.unobtrusive.parse(document);

var onSuccess = function (divContactInfo) {
    // enable unobtrusive validation for the contents
    // that was injected into the <div id="result"></div> node
    //$.validator.unobtrusive.parse($(divContactInfo));


    //        var form = $('#testform')
    //            .removeData("validator") /* added by the raw jquery.validate plugin */
    //            .removeData("unobtrusiveValidation");  /* added by the jquery unobtrusive plugin */

    //  $.validator.unobtrusive.parse(form);

};



</script>

 <% Html.EnableClientValidation(); %>

 <% using (Ajax.BeginForm("Index", "Home", new AjaxOptions
 {
   OnBegin = "onSuccess",
   UpdateTargetId = "divContactInfo"
 }, new { @id = "testform" }))
 {%>
 <%: Html.ValidationSummary(true)%>
 <fieldset>
<legend>Fields</legend>
<div class="editor-label">
    <%: Html.LabelFor(model => model.name)%>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.name)%>
    <%: Html.ValidationMessageFor(model => model.name)%>
</div>
<p>
    <input type="submit" value="Create" />
</p>
</fieldset>
<% } %>

Това е моят контролер:

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(TestDA model)
    {

        if (ModelState.IsValid)
        {

        }
        else
        {

        }

        return View("test", model);
    }
    public ActionResult test()
    {
        return PartialView("test");
    }
}

Това е моят модел:

public class TestDA
{
    [Required]
    [DisplayName("Your Name")]
    public string name { get; set; }
}

person Naresh Parmar    schedule 31.05.2013    source източник
comment
Тези неща работят перфектно с друго демо приложение. Но не и в нашето приложение на живо. Мисля, че противоречи на Телерик. Възможно ли е ?   -  person Naresh Parmar    schedule 03.06.2013


Отговори (1)


Реших го, като добавих по-долу скриптов блог:

<script type="text/javascript">
Sys.Mvc.FormContext._Application_Load();
$("#form0").submit(function (e) {
    if (!Sys.Mvc.FormContext.getValidationForForm(this).validate('submit').length) {
        $.post("/ManageUser/SaveContactInfo", $(this).serialize(), function (data) {
            $("#divContactInfo").html(data);
        });
    }
    e.preventDefault();
});
</script>

За повече информация прочетете това:

http://weblogs.asp.net/imranbaloch/archive/2010/07/11/asp-net-mvc-client-side-validation-with-dynamic-contents.aspx

person Naresh Parmar    schedule 03.06.2013