Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.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
Ajax MVC将部分视图返回为JSON_Ajax_Asp.net Mvc_Validation - Fatal编程技术网

Ajax MVC将部分视图返回为JSON

Ajax MVC将部分视图返回为JSON,ajax,asp.net-mvc,validation,Ajax,Asp.net Mvc,Validation,作为MVC JSON响应的一部分,是否有一种方法可以通过呈现部分来返回HTML字符串 public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model) { if (ModelState.IsValid) { if(Request.IsAjaxRequest() return PartialView("NotEvil",

作为MVC JSON响应的一部分,是否有一种方法可以通过呈现部分来返回HTML字符串

    public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
    {
        if (ModelState.IsValid)
        {
            if(Request.IsAjaxRequest()
                return PartialView("NotEvil", model);
            return View(model)
        }
        if(Request.IsAjaxRequest())
        {
            return Json(new { error=true, message = PartialView("Evil",model)});
        }
        return View(model);
    }

您可以从PartialViewResult对象中提取html字符串,类似于此线程的答案:

PartialViewResult和ViewResult都派生自ViewResultBase,因此相同的方法应该适用于这两者

使用上述线程中的代码,您将能够使用:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
    if (ModelState.IsValid)
    {
        if(Request.IsAjaxRequest())
            return PartialView("NotEvil", model);
        return View(model)
    }
    if(Request.IsAjaxRequest())
    {
        return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
    }
    return View(model);
}

我不喜欢
RenderViewToString

return Json(new { Url = Url.Action("Evil", model) });
然后,您可以在javascript中捕获结果并执行以下操作

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

好办法。然后将视图呈现为字符串。但它需要更多的http请求。但这会在json响应中忽略“error”字段。
Url.Action(“邪恶”,model)
将生成get查询字符串,但您的ajax方法是post,它将抛出错误状态500(内部服务器错误).如果它是一个调用ReturnSpecialJsonIfInvalid的ajax调用,我相信它会返回一些数据。jquery如何区分视图和json?RenderViewToString()方法的定义在哪里?@Sinjai没有带有
PartialViewResult
参数的
RenderViewToString
方法。但也有类似的其他方法。在这里插入方法会很有用。如何传递集合的对象,例如ToList()或AsQueryable()对象?