MVC3(Razor)如何用json在Controller中传递数据

时间:2012-06-06 10:29:33

标签: asp.net-mvc json razor

我已经使用以下jQuery Ajax代码将View中的模型传递给Controller:

$.ajax({
        data: model,
        type: "POST",
        url: '@Url.Action("createDoc")',
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            alert('Done '+ result.toString());
        }
    });

问题是:在Controller方法“createDoc”

[HttpPost]
    public ActionResult createDoc(IEnumerable<Movie> movies)
    {
        CreateWordprocessingDocument(movies);
        return Json(new { result = movies.Count()});
    }

我对电影无法做任何事情。 对CreateWordProcessingDocument的调用会创建包含电影数据的文档。但事实并非如此。 这是方法代码:

public void CreateWordprocessingDocument(IEnumerable<Movie> movies)
{
    HttpContextWrapper context = new HttpContextWrapper(System.Web.HttpContext.Current);
    context.Response.Clear();
    context.Response.Buffer = true;
    context.Response.AddHeader("content-disposition", "attachment;filename=example.doc");
    context.Response.ContentType = "application/vnd.ms-word.document";
    context.Response.Charset = "";
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("<p  align='Center'><b> GENERAL TITLE</b></p>");
    sb.Append("<br>"+movies.Count());
    for (int i = 0; i < movies.Count(); i++) {
        sb.Append("<br>Title:" + movies.ElementAt(i).Title +"");
    }
    context.Response.Output.Write(sb.ToString());
    context.Response.Flush();
    context.Response.End();
}

但它不起作用:它返回到ajax帖子并弹出“完成”警报,result.tostring()显示我在createWordProcessingDocument方法上创建的HTML代码。 如何避免这种行为,以便我可以对从View中传递给控制器​​的数据做些什么? 感谢。

3 个答案:

答案 0 :(得分:1)

ASP.net MVC包含一个FileResult,以便将带有mime类型的文件返回给浏览器。

做这样的事情:

public ActionResult  createDoc(IEnumerable<Movie> movies)
{
    byte[] fileContents = CreateFileFromMovies(movies);

    return File(fileContents, "application/vnd.ms-word.document");
}

不是直接访问响应,而是将文档创建为字节数组,并使用File()方法返回内容。

答案 1 :(得分:1)

问题解决了:我在这里发布解决方案,如果它可以帮助解决我的问题的人。 在我的 createDoc 方法中,我创建了包含所需数据的字符串,然后我将它们放在tempData属性中。这就是 createDoc 的样子:

[HttpPost]
    public void createDoc(IEnumerable<Movie> movies)
    {
        String mov="";
        mov = mov + "<br>" + movies.Count();
        for (int i = 0; i < movies.Count(); i++)
        {
           mov=mov+"<br>Title:" + movies.ElementAt(i).Title + "";
        }
        TempData["movies"] = mov;
    }

然后“控件”返回到Ajax post方法,最后我把它放在:

success: function (result) {
            window.location.href = '@Url.Action("CreateWordprocessingDocument","Movies")'
        }

所以我的Ajax发布完整代码是:

<script type="text/javascript">
function postData() {
    var urlact = '@Url.Action("createDoc")';
    var model = '@Html.Raw(Json.Encode(Model))';

    alert(model);
    alert(JSON.stringify(model));

    $.ajax({
        data: model,
        type: "POST",
        url: urlact,
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            window.location.href = '@Url.Action("CreateWordprocessingDocument","Movies")'
        }
    });
}
</script>

现在“控件”重定向到 CreateWordProcessingDocument 操作,我实际创建了文档:

public void CreateWordprocessingDocument()
    {
        string movies = TempData["movies"] as string;
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.AddHeader("content-disposition", "attachment;filename=example.doc");
        context.Response.ContentType = "application/vnd.ms-word.document";
        context.Response.Charset = "";
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("<p  align='Center'><b>TITLE</b></p>");
        sb.Append(movies);
        context.Response.Output.Write(sb.ToString());
        context.Response.Flush();
        context.Response.End();
    }

这就是全部。感谢大家的帮助,希望我能帮助解决这个问题的人。

答案 2 :(得分:0)

您获取在CreateWordprocessingDocument中创建的HTML代码的原因是因为您直接输出到HTTP响应。然后你结束了回复。基本上,你通过直接自己编写响应来绕过很多ASP.NET MVC。