2010-04-13 101 views
0

我想完成的是一个partiel视图包含一个表单。此表单使用JQuery $ .post发布。在成功发布javascript后,获取结果并使用JQuery的html()方法填充结果的容器。返回一个JSON视图和一个布尔值

但是,现在我不想返回部分视图,而是包含该部分视图和其他某个对象(本例中为Success - > bool)的JSON对象。

我用下面的代码试了一下:

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Edit(int id, Item item) 
    { 
     if (ModelState.IsValid) 
     { 
      try 
      { 
       // ... 
       return Json(new 
       { 
        Success = true, 
        PartialView = PartialView("Edit", item) 
       }); 
      } 
      catch(Exception ex) 
      { 
       // ... 
      } 
     } 

     return Json(new 
     { 
      Success = false, 
      PartialView = PartialView("Edit", item) 
     }); 
    } 

但是我并不在此JSON对象获取的HTML,并且不能用html()来显示结果。我尝试使用this方法将部分呈现为Html并发送该内容。但是,对于RenderControl(tw)方法,这会失败:方法或操作未实现。

+0

您确定您创建的PartialView可以序列化为JSON吗?此外,Json方法做了什么?它是否序列化传递的内容?为什么你有两个return语句返回完全相同的东西:) – 2010-04-13 09:15:28

+0

是的,partialview可以被序列化为JSON。不,我不会两次返回相同的东西。一次有效验证,一次无效。但不知怎的,我从这样的方法得到了不安,但是我无法给出更好的方法。 – 2010-04-13 10:00:32

回答

0

好了,找到了原因此页面上的代码:
Render a view as a string
没有奏效。

愚蠢:我必须包含System.Web.Mvc.Html才能在HtmlHelper对象上使用renderpartial。

但是我并没有真正相信这个解决方案。必须有一个更清洁的方式?

1

是的,有一种更清洁的方式(我认为也更容易)。使用MVC AJAX帮手。

例如,在您的视图:

<% using (Ajax.BeginForm("Edit", new { id = Model.Id}, 
    new AjaxOptions 
    { 
     UpdateTargetId = "divId", //id of the container 
     OnFailure= "function(){ alert('Error');}" //can be a callback too 
    })) 
    { %> 
在你的控制器

然后:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Edit(int id, Item item) 
{ 
    if (ModelState.IsValid) 
    { 
     try 
     { 
      // ... 
      return PartialView("Edit", item); //your container will be updated with this content 
     } 
     catch(Exception ex) 
     { 
      // ... 
      return ReturnStatusCodeError("Item not found", HttpStatusCode.NotFound); //the ajax script will catch this error and fire the OnFailure event 
     } 
    } 

    return ReturnStatusCodeError("Error", HttpStatusCode.Conflict); //can be changed to an error of your preference 
} 


protected ActionResult ReturnStatusCodeError(string error, HttpStatusCode code) 
{ 
    Response.StatusCode = (int)code; 
    Response.Write(error); 
    Response.End(); 

    //redundant. Just for compiler compliance 
    return View(); 
} 

这样,你的容器可以自动更新和提交成功。如果出现错误,您可以做一些更复杂的配置“OnFailure”ajax选项。