c# - 查看帖子中的 PartialView 并返回响应 json

标签 c# asp.net-mvc asp.net-ajax

我的 PartialView 是在 View 中渲染的,那么这个 PartialView 需要 post Controller ,并捕获响应,然后显示。怎么办?

查看

<div class="row">
        <div id="partialViewContainer"></div>
    </div>

部分 View

@model foo

@using (Html.BeginForm("UploadFile", "ManageFiles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    //Some Html
    <div id="ResponsePost">
    </div>
}

Controller

[HttpPost]
public JsonResult UploadFile(UploadFileViewModel m)
{        
            if (!ModelState.IsValid)
            {
                var errorList = (from item in ModelState
                             where item.Value.Errors.Any()
                             select item.Value.Errors[0].ErrorMessage).ToList();

                    return Json(errorList);
            }

            //Some Logic             
            var foo = new { ... };
            return Json(foo);
}

最佳答案

我认为最简单的方法是使用 Ajax.BeginForm 扩展而不是 Html.BeginForm。代码少,易读。

权衡是您需要将 jquery.unobtrusive-ajax.js 与 Jquery 一起包含。

@using (Ajax.BeginForm("UploadFile","ManageFiles" , new AjaxOptions() {  OnSuccess = "getResult" }))

这里,getResult 用于定义 Ajax 请求成功后将触发的 JavaScript 函数。

然后你可以这样写:

function getResult(data){
    $('#ResponsePost').append('<p>' + data.message + '</p>');
}

关于c# - 查看帖子中的 PartialView 并返回响应 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46552417/

相关文章:

c# - 将对象转换为字节数组

c# - 处理繁琐的 string.Split 重载?

javascript - 在 ASP.NET MVC : All possible ways to call Controller Action Method from a Razor View

javascript - 使用 Jquery 和 Soap-XML 连接到 WCF Web 服务

asp.net-mvc - 阻止从 URL 而不是 Ajax 调用访问部分 View

c# - 如何编写与 ViewModel 类绑定(bind)的嵌套类?

c# - Designer.Cs 文件未注册命名空间更新

c# - 使用 MVC 打开一个新窗口

c# - ASP.NET MVC 4 模型绑定(bind)问题

ASP.net Ajax 选项卡容器未出现