MVC和AJAX与JQuery

时间:2010-11-01 17:50:29

标签: jquery ajax asp.net-mvc

通过查看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);

        }

3 个答案:

答案 0 :(得分:2)

您问题的最直接答案是。是的!

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

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

如果你只是在表单上做一些简单的错误检查。一定要做一个基本的html表单帖子,返回内置到你的MVC实现中。

如果你真的使用你的部分作为部分,并做一些像民意调查或其他嵌入式表格系统,重新加载整个页面是不可接受的,那么AJAX就是你的票。

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

答案 1 :(得分:1)

我发现你的问题存在两个问题。

  1. 您是否研究过您的条款? jQuery通常用于执行AJAX操作,MVC代表模型 - 视图 - 控制器,这是服务器端代码结构(视图和服务代码分离)的一种方式。 JSON可以用于数据交换和操作(有点像XML,只是更简单),并且在使用表单时不是必需的。
  2. 您还没有告诉我们您的服务器端技术是什么。虽然表单是html规范的基本部分,但您仍然必须在服务器端以某种方式处理它们。

答案 2 :(得分:0)

我在下面做了,它在MVC 3中为我工作。

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

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

在函数下面用于在控制器的Action方法中获取字符串中的部分视图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);
                }
            }
        });
    }
}

<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>

<强> 2。 Form1PartialView

@using (Html.BeginForm("Action1", "Controller", FormMethod.Post, new { @id = "Form1" }))
{
    <!-Form elements go here->                    
    <button type='submit'>Submit Form1</button>
}

第3。 Form2PartialView

@using (Html.BeginForm("Action2", "Controller", FormMethod.Post, new { @id = "Form2" }))
{
   <!-Form elements go here->                    
   <button type='submit'>Submit Form2</button>
}

<强> 4。 Form3PartialView

@using (Html.BeginForm("Action3", "Controller", FormMethod.Post, new { @id = "Form3" }))
{
    <!-Form elements go here->                    
    <button type='submit'>Submit Form3</button>
}

<强> 5。控制器代码

[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) });
}