【问题标题】:Can i return a Partial view and a Json object from my action method at the same time我可以同时从我的操作方法返回一个部分视图和一个 Json 对象吗
【发布时间】:2012-05-03 13:40:22
【问题描述】:

我有以下操作方法,它返回部分视图_create。但是有没有办法通过 Partial 视图传递 Json 对象,例如 return Json(new { IsSuccess = "True" },

我的 Action 方法如下:-

try
{
  if (ModelState.IsValid)
  {
     var v = repository.GetVisit(visitid);
     if (!(v.EligableToStart(User.Identity.Name)))
     { 
       return View("NotFound"); 
     }
     vlr.VisitID = visitid;
     repository.AddVisitLabResult(vlr);
     repository.Save();
     ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", vlr.LabTestID);
     // return Json(new { IsSuccess = "True" }, JsonRequestBehavior.AllowGet);
     @ViewBag.status = "Added Succsfully";
     return  PartialView("_create",vlr) ;
   }
}

::-UPDATED-::

我想要做的事情如下:-

  1. 我正在使用 ajax.beginform 调用操作方法

    using (Ajax.BeginForm("CreateAll", "VisitLabResult", new AjaxOptions
    {
      HttpMethod = "Post",
      UpdateTargetId = item.ToString(),
      InsertionMode = InsertionMode.Replace,
      OnSuccess = string.Format("disableform({0})", Json.Encode(item)),
    }))
    
  2. 成功接收到服务器的响应后,会执行Onsuccess脚本,,脚本只是禁用表单:-

    function disableform(id) {
        $('#' + id + ' :input').prop("disabled", true);
    }
    

问题是 脚本将始终禁用表单,即使发生一些验证错误,所以我试图实现的是返回一个带有部分视图的 JSON,该部分视图指示 ModelState .IsValid 是否有效,如果无效,请保持表单启用以允许用户更正验证错误。

BR

【问题讨论】:

    标签: json asp.net-mvc-3


    【解决方案1】:

    你只能从 action 方法返回一个视图,如果你想传递其他信息,请使用 ViewData 或 ViewBag

    ViewBag.IsSuccess =  "True";
    

    或者

    ViewData["IsSuccess"] = "True";
    

    【讨论】:

      【解决方案2】:

      不,你可以只返回视图并传递 JSON 作为模型,或者 ViewBag(我推荐模型。)

      【讨论】:

      • 我认为 viewbag 和 viewmodel 都不能解决我的问题,请检查我的更新以查看我面临的问题的更多详细信息
      【解决方案3】:

      为什么不简单地扩展您已经传递给视图的模型,添加属性IsSuccess

      在我看来,ViewBag 或 ViewData 是邪恶的。尝试在将数据返回到视图时始终使用 ViewModel。

      【讨论】:

        【解决方案4】:

        在这种情况下,我使用了以下解决方案:

        在您的 ajax 表单定义集中:

        OnComplete = "yourCallback"
        

        然后:

        yourCallback = function(response){
          var json = response.responseJSON;
          if(json.success){
             alert('Well done!');
          } else {
             var form = $('#formId');
             form.html(json.html);
             form.removeData("validator").removeData("unobtrusiveValidation");
             $.validator.unobtrusive.parse(form);
          }
        }
        

        您的控制器应该返回如下内容:

        var result = new { success = false, html = helper.Partial("_YourPartial", model) };
        return Json(result);
        

        helper 可帮助您向局部视图添加验证。 (此处描述:https://stackoverflow.com/a/4270511/952023

        【讨论】:

          猜你喜欢
          • 2012-01-30
          • 2012-05-13
          • 1970-01-01
          • 1970-01-01
          • 2018-10-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-28
          • 2013-09-11
          相关资源
          最近更新 更多