4

好吧,我有简单的 ajax 形式:

这是MyPartialView

@using(Ajax.BeginForm("action", "controller", new AjaxOptions
{
    OnBegin = "beginRequest",
    OnComplete = "completeRequest",
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "div-to-replace"
}, }))
{
    <input type="text" id="my-input" /> 
    ...
}

这是父视图:

<div id="div-to-replace">
    @Html.RenderPartial("MyPartialView")
</div>

在我的控制器中,我有:

[HttpPost]
public ActionResult action(Model model)
{
   if (ModelState.IsValid)
   {
      // do staff with model
      // return partial view
      return PartialView("MyPartialView");
   }
   // else add error and return json result
   return Json(new {error = "invalid data"});
}

还有我的 ajax 完整方法上的 javascript:

function completeRequest(data) {
    var result = $.parseJSON(data.responseText);

    if (result != 'undefined' && result != null && result.error) {
        // just display error and not replace  all content
        // attachModelError is my custom method, it just adds vlaidation-error class to inputs, etc.
        attachModelError("my-input", result.error);
        return;
    }

    // or show returned html (depending on returned model form inputs will be modified:
    // select box with different items in my case
    $('#div-to-replace').html(data.responseText);
}

#div-to-replace但问题是如果模型状态无效,我有空。如果模型状态正常,则一切正常。如果我使用不同的插入模式,它会在 div 之前或之后创建 div 内容的副本。

摘要:
我想要InsertionMode根据json结果不同的行为。我不需要替换数据if (result != 'undefined' && result != null && result.error)

4

2 回答 2

6

很久以前我不得不解决这个问题。我想出了一个简单的解决方案,今天它可能不是最好的解决方案,但它可以完成工作。

我的解决方案涉及设置一个控制器操作,该操作将仅使用它需要的数据呈现部分,并让我的 JavaScript 请求它。

C#

MyController: Controller 
{
  public ActionResult GetPartialViewAction()
  {
    return PartialView("mypartialview", new partialViewModel());
  }
}

JavaScript

$.ajax({
  url: "/my/getpartialaction/"
}).done(function(data) {
  $("#partialViewDiv").html(data);
});

HTML

<div id="partialViewDiv"></div>

更好的解决方案是使用 MVVM/MVC JavaScript 库,它允许您利用 html 模板,并且只需通过 ajax 解决方案传输数据。我建议查看 knockout.js 或bone.js 以获得这种更被接受的模式。

于 2013-08-08T19:34:57.140 回答
1

我对默认的 c# ajax 表单有同样的问题。我有一个可行的解决方案。

jQuery:

$(function () {

var ajaxFormSubmit = function () {

    var $form = $(this);

    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize(),
        cache: false
    }

    $.ajax(options).done(function (data) {

        data.replaces.each(function (replace) {

            $(replace.id).replaceWith(replace.html);

        });

    });

    return false;
};

$("form[data-ajax='true']").submit(ajaxFormSubmit);});

表单.cshtml

@using (Html.BeginForm("Create", "Menu", FormMethod.Post, new { data_ajax = "true" }))
{}

模型样本

public string Id {get;set;}
public string Html {get;set;}

您需要在控制器中做的最后一件事是返回一个带有模型示例列表的 json 结果,id 是要更新的目标元素,对于 html,您必须使用渲染部分 / 或视图作为字符串。

对于部分渲染视图,请参阅 [问题]:https ://stackoverflow.com/questions/434453

于 2013-11-26T15:31:06.773 回答