不显眼的Ajax调用不发送查看模型返回到控制器
问题描述:
我已经在我的cshtml详细信息视图中获得此代码。我想将VM发送回该控制器方法。这可以工作,因为我可以在控制器中设置断点,但模型为空。下面是客户端不显眼的Ajax调用不发送查看模型返回到控制器
function downLoadFile() {
$.ajax({
url: '/Software/DownLoadInstall',
type: "POST",
data: JSON.stringify('@Model'),
datatype: "json",
contentType: "application/json; charset=utf-8"
});
}
,并在这里是我的控制器看起来像
[HttpPost]
public ActionResult DownLoadInstall(SoftwareEditViewModel vm)
{
try
{
SoftwareService.DownLoadInstall(vm);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
答
我认为这是不可能的复杂模型会产生一个合理的字符串表示JSON.stringify可以使用。只需传递要下载的项目的标识(可能包含在模型中)即可。如果下载意味着我的想法,那么它确实应该返回一个FileResult,并且之后不应该重定向。也不需要使用AJAX,因为文件下载不会将您带离页面。我根据你的命名做出一些大的假设 - 如果我错了,你真的应该使用更好的名字。
[HttpPost]
public ActionResult DownLoadInstall(int id)
{
return SoftwareService.DownLoadInstall(ModelFromID(id));
}
private SoftwareViewModel ModelFromID(id)
{
... populate the model needed for download from id ...
}
客户
function downLoadFile() {
location.href = '/software/downloadinstall/' + @Model.ID;
}
答
调用@Model
就叫ToString()
的对象。
您需要先将Model
转换为json。
例扩展方法
public static class JsonHelperExtensions
{
static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public static string ToJson(this object o)
{
return Serializer.Serialize(o);
}
}
在jQuery函数
然后:
function downLoadFile() {
$.ajax({
url: '/Software/DownLoadInstall',
type: "POST",
data: JSON.stringify('@Model.ToJson()'),
datatype: "json",
contentType: "application/json; charset=utf-8"
});
}
tvanfosson THX ......你这样做是正确有关目的。我们公司有30个直流电,每个国家都有自己的本地驱动器映射可下载软件。所以,我必须使用Response.WriteFile将文件流式传输回来,然后执行“net use”从适当的登录服务器下载文件。我不遵循我不需要使用Ajax。我有两个按钮和详细信息页面...他们可以下载和查看帮助文件,或者他们可以下载实际安装。对不起,如果TMI我这个小纸条。 Thx的伟大答复。 – Bayrat 2011-03-17 12:54:12
直到你刚刚提到它,你甚至都不知道FileResult。这看起来像要走的路......我以传统的ASPX模式构建了这个应用程序的原型,现在已经在MVC3中重做了它......这是一个巨大的帮助,感谢参考...这里是一个伟大的写作它http://*.com/questions/1187261/whats-the-difference-between-the-four-file-results-in-asp-net-mvc – Bayrat 2011-03-17 13:09:10