不引人注意的Ajax调用不会将View Model发送回Controller

时间:2011-03-17 12:28:52

标签: ajax jquery asp.net-mvc-3 asp.net-ajax

我的cshtml详细信息视图中有这个代码。我想将VM发送回此控制器方法。这可以工作,因为我可以在控制器中设置断点,但模型为空。这是客户端

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();
        }
    }

2 个答案:

答案 0 :(得分:3)

我认为复杂模型不太可能产生JSON.stringify可以使用的合理字符串表示。你最好只传递你想要下载的项目的ID(可能包含在模型中)。如果下载意味着我的想法,它确实应该返回一个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;
}

答案 1 :(得分:2)

调用@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"
     });
}