Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MVC和AJAX与JQuery_Jquery_Ajax_Asp.net Mvc - Fatal编程技术网

MVC和AJAX与JQuery

MVC和AJAX与JQuery,jquery,ajax,asp.net-mvc,Jquery,Ajax,Asp.net Mvc,我看了这么多JQuery和AJAX与MVC一起使用的方法,真的很困惑,而且我没有找到合适的文档 在我的应用程序中,我有一个非常常见的场景,其中我有一个表单,它是一个部分视图,用户将提交该表单,如果该表单有效,则将其存储到数据库中,如果无效,则再次向用户显示同一表单,并在页面上显示错误 最简单的方法是什么?我可以使用简单的AJAXForm来实现这一点,还是还必须使用JSON和JQuery <script type="text/javascript"> functio

我看了这么多JQuery和AJAX与MVC一起使用的方法,真的很困惑,而且我没有找到合适的文档

在我的应用程序中,我有一个非常常见的场景,其中我有一个表单,它是一个部分视图,用户将提交该表单,如果该表单有效,则将其存储到数据库中,如果无效,则再次向用户显示同一表单,并在页面上显示错误

最简单的方法是什么?我可以使用简单的AJAXForm来实现这一点,还是还必须使用JSON和JQuery

 <script type="text/javascript">

        function successContactList() {
               alert("Success.");
      }

        function failureContactList() {
            alert("Error.");
        }

    </script>


    <% using (Ajax.BeginForm("SaveMailingList", "Contacts", new AjaxOptions { OnFailure = "failureContactList", OnComplete = "successContactList", UpdateTargetId = "ContactArea" })) { %>
    <div id="ContactArea">

        <%: Html.EditorFor(Model => Model)  %>
         <input type="submit" value="Save" />
    </div>
    <% } %>



    [HttpPost]
        public ActionResult SaveMailingList(IEnumerable<ContactsInMailingListsViewModel>  contactInMailing) {
            var mailingList = contactInMailing.FirstOrDefault();
            var contact = repository.GetContactById(mailingList.ContactId);
            repository.UpdateMailingList(contactInMailing,contact);
            contactInMailing.FirstOrDefault().EndDate = new DateTime(2077,1,1);
            return PartialView(contactInMailing);

        }

函数successContactList(){
警惕(“成功”);
}
功能故障联系人列表(){
警惕(“错误”);
}
型号)%%>
[HttpPost]
公共操作结果保存邮件列表(IEnumerable ContactinMail){
var mailingList=contactInMailing.FirstOrDefault();
var contact=repository.GetContactById(mailingList.ContactId);
repository.updateEmailingList(contactInMailing,contact);
ContactInMail.FirstOrDefault().EndDate=新的日期时间(2077,1,1);
返回PartialView(联系mailing);
}

我发现你的问题有两个问题

  • 你研究过你的条件了吗?jQuery通常用于进行AJAX操作,MVC代表Model-View-Controller,这是服务器端代码结构化的一种方法(视图和服务代码分离)。JSON可以用于数据交换和操作(有点像XML,只是更简单),并且在使用表单时不需要JSON
  • 您还没有告诉我们您的服务器端技术是什么。尽管表单是html规范的基本部分,但您仍然必须在服务器端以某种方式处理它们

  • 对你的问题最直接的回答是。对!

    AJAX和MVC是抽象概念。在实现环境之外,它们真的意义不大。例如,JQuery实现了AJAX的概念,Symphony实现了MVC的概念

    你需要做什么?你的要求是什么?你想要什么样的用户体验

    如果您只是在表单上执行一些简单的错误检查。无论如何,只需在MVC实现中内置一个基本的html表单post、return

    如果您真的将partial用作partial,并执行诸如轮询或其他嵌入式表单系统之类的操作,其中不允许重新加载整个页面,那么AJAX就是您的选择


    至于使用什么实现。我想看看你的MVC内置了什么。如果出于某种原因,它还没有提供ajax系统。我个人喜欢JQuery。

    我在下面做了,它在MVC 3中对我起了作用

    在我的场景中,页面上有3个表单(3个部分视图),我只希望它们通过ajax提交并更新相应的部分视图

    动态更新表单后,需要添加回提交事件处理程序,并调用$.validator.unobtrusive.parse('#Form1);为下一次提交进行客户端验证

    下面的函数用于在控制器的操作方法中获取字符串形式的部分视图html

    //Renders Partial View as a string
    //Parameters: Calling Controller Context, partial view name, model
    //Reference:http://stackoverflow.com/questions/3234003/render-view-programmatically-into-a-string
    public static string RenderPartialViewToString(ControllerContext context, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = context.RouteData.GetRequiredString("action");
    
            context.Controller.ViewData.Model = model;
    
            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
                ViewContext viewContext = new ViewContext(context, viewResult.View, context.Controller.ViewData, context.Controller.TempData, sw);
                // copy model state items to the html helper 
                foreach (var item in viewContext.Controller.ViewData.ModelState)
                    if (!viewContext.ViewData.ModelState.Keys.Contains(item.Key))
                    {
                        viewContext.ViewData.ModelState.Add(item);
                    }
    
                viewResult.View.Render(viewContext, sw);
    
                return sw.GetStringBuilder().ToString();
            }
        }
    

    1。索引视图-

    <script type='text/javascript'>
        $(document).ready(function () {
    
        //Add Event handlers for the forms after document is ready.
        $("#Form1").submit(Form1SubmitHandler);
    
        $("#Form2").submit(Form2SubmitHandler);
    
        $("#Form3").submit(Form3SubmitHandler);
    });
    
    //Submit Event handler for Form1Form
    function Form1SubmitHandler(event) {
        event.preventDefault();
        if ($("#Form1").valid()) {
            Form1Ajax();
        }
    }
    
    //Submit Event handler for Form2 Form
    function Form2SubmitHandler(event) {
        event.preventDefault();
        if ($("#Form2").valid()) {
            Form2Ajax();
        }
    }
    
    //Submit Event handler for Form3 Form
    function Form3SubmitHandler(event) {
        event.preventDefault();
        if ($("#Form3").valid()) {
            Form3Ajax();
        }
    }
    
    //Submit Form1
    function Form1Ajax() {
        if ($("#Form1").valid())
        {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("Action1", "Controller")',
                cache: false,
                data: { //send your form values here
                },
                dataType: "json",
                success: function (data) {
                    if (data.IsSuccess) {
    
                        //Update the partial view.
                        $("#Form1Partial").html(data.ViewHtml);
    
                        //Have to call this to make client side validation work after dynamically adding a form.
                        $.validator.unobtrusive.parse('#Form1');
    
                        //Add event handler for submit.
                        $("#Form1").bind("submit", Form1SubmitHandler);
                    }
                    else {
    
                        //Update the partial view.
                        $("#Form1Partial").html(data.ViewHtml);
    
    
                        //Have to call this to make client side validation work after dynamically adding a form.
                        $.validator.unobtrusive.parse('#Form1);
    
                        //Add event handler for submit.
                        $("#Form1").bind("submit", Form1SubmitHandler);
                    }
                }
            });
        }
    }
    
    //Submit Form2
    function Form2Ajax() {
        if ($("#Form2").valid())
        {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("Action2", "Controller")',
                cache: false,
                data: { //send your form values here
                },
                dataType: "json",
                success: function (data) {
                    if (data.IsSuccess) {
    
                        //Update the partial view.
                        $("#Form2Partial").html(data.ViewHtml);
    
                        //Have to call this to make client side validation work after dynamically adding a form.
                        $.validator.unobtrusive.parse('#Form2');
    
                        //Add event handler for submit.
                        $("#Form2").bind("submit", Form2SubmitHandler);
                    }
                    else {
    
                        //Update the partial view.
                        $("#Form2Partial").html(data.ViewHtml);
    
    
                        //Have to call this to make client side validation work after dynamically adding a form.
                        $.validator.unobtrusive.parse('#Form2);
    
                        //Add event handler for submit.
                        $("#Form2").bind("submit", Form2SubmitHandler);
                    }
                }
            });
        }
    }
    
    //Submit Form3
    function Form3Ajax() {
        if ($("#Form3").valid())
        {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("Action3", "Controller")',
                cache: false,
                data: { //send your form values here
                },
                dataType: "json",
                success: function (data) {
                    if (data.IsSuccess) {
    
                        //Update the partial view.
                        $("#Form3Partial").html(data.ViewHtml);
    
                        //Have to call this to make client side validation work after dynamically adding a form.
                        $.validator.unobtrusive.parse('#Form3);
    
                        //Add event handler for submit.
                        $("#Form3").bind("submit", Form3SubmitHandler);
                    }
                    else {
    
                        //Update the partial view.
                        $("#Form3Partial").html(data.ViewHtml);
    
    
                        //Have to call this to make client side validation work after dynamically adding a form.
                        $.validator.unobtrusive.parse('#Form3);
    
                        //Add event handler for submit.
                        $("#Form3").bind("submit", Form3SubmitHandler);
                    }
                }
            });
        }
    }
    

    很抱歉,我的标题有点让人困惑。我使用的是ASP.NET MVC 2。目前我在MVC中使用的是Ajax.BeginForm。问题是它调用了控制器操作,但我认为在操作完成后视图不会更新。我已经更新了上面实际问题中的代码。@Mathew:对不起,我没有使用ASP.NET,所以我帮不了你。我希望其他人能够提供帮助。谢谢你的回复。我已经更新了代码,以备你检查。
    <div id="Form1Partial">@Html.Partial("Form1Partial", Model.model1)</div>
    <div id="Form2Partial">@Html.Partial("Form2Partial", Model.model2)</div>
    <div id="Form3Partial">@Html.Partial("Form3Partial", Model.model3)</div>
    
    @using (Html.BeginForm("Action1", "Controller", FormMethod.Post, new { @id = "Form1" }))
    {
        <!-Form elements go here->                    
        <button type='submit'>Submit Form1</button>
    }
    
    @using (Html.BeginForm("Action2", "Controller", FormMethod.Post, new { @id = "Form2" }))
    {
       <!-Form elements go here->                    
       <button type='submit'>Submit Form2</button>
    }
    
    @using (Html.BeginForm("Action3", "Controller", FormMethod.Post, new { @id = "Form3" }))
    {
        <!-Form elements go here->                    
        <button type='submit'>Submit Form3</button>
    }
    
    [HttpPost]
    public ActionResult Action1(Model model)
    {
     if (ModelState.IsValid)
     {
        //Do some thing
    
        return Json ( new { IsSuccess = true, ViewHtml = RenderPartialViewToString(ControllerContext, "Form1Partial", model) });     
    
     }
    
      // If we got this far, something failed,
      return Json ( new { IsSuccess = false, ViewHtml = RenderPartialViewToString(ControllerContext, "Form1Partial", model) });
    }
    
    [HttpPost]
    public ActionResult Action2(Model model)
    {
     if (ModelState.IsValid)
     {
        //Do some thing
    
        return Json ( new { IsSuccess = true, ViewHtml = RenderPartialViewToString(ControllerContext, "Form2Partial", model) });     
    
     }
    
      // If we got this far, something failed,
      return Json ( new { IsSuccess = false, ViewHtml = RenderPartialViewToString(ControllerContext, "Form2Partial", model) });
    }
    
    [HttpPost]
    public ActionResult Action3(Model model)
    {
     if (ModelState.IsValid)
     {
        //Do some thing
    
        return Json ( new { IsSuccess = true, ViewHtml = RenderPartialViewToString(ControllerContext, "Form3Partial", model) });     
    
     }
    
      // If we got this far, something failed,
      return Json ( new { IsSuccess = false, ViewHtml = RenderPartialViewToString(ControllerContext, "Form3Partial", model) });
    }