返回File时,使用对ActionResults的MVC3 AJAX调用失败

时间:2012-01-12 16:03:11

标签: ajax asp.net-mvc-3

我有一个动作结果,返回一个创建的File对象(简化显示!):

public ActionResult Create(int recID, int templateID)
{
    //Get dbRecord from recID
    DBRecord dbRecord = db.dbRecord.Find(recID);

    //Get Template from templateID
    Template template = db.Templates.Find(templateID);
    if (template == null) throw new FileLoadException(string.Format("No database record found for template reference {0}",templateID));

    //set fileOutput details
    WordFile fileOutput = new WordFile(dbRecord, Server.MapPath("~/Documents/"),template);

    //Create XML object for Template
    XmlDocument xDoc = new XmlDocument();

    //Save resulting document
    xDoc.InnerXml = mergeData(template,dbRecord);
    xDoc.Save(fileOutput.fullName);
    if (!System.IO.File.Exists(fileOutput.fullName)) throw new FileNotFoundException(string.Format("File {0} could not be created", fileOutput.fileName));

    //Return saved document
    return File(fileOutput.fullName, "application/doc", fileOutput.fileName);
}

如果我通过HTML RouteLink调用它

<%: Html.RouteLink("Generate via HTML
        , "GenerateDocument"
        , new RouteValueDictionary(
            new { 
                    controller = "Template"
                    , action = "Create"
                    , recID = 1
                    ,templateID = 1
                }
            )
        )%>

编辑1:它工作正常,生成文档并提示用户打开,保存等。但是,如果我通过AJAX RouteLink调用它,代码将逐步完成,文档是在服务器上创建的,但系统不会提示用户打开或保存。

<%: Ajax.RouteLink("Generate via AJAX"
        , "GenerateDocument"
        , new RouteValueDictionary(
            new { 
                    controller = "Template"
                    , action = "Create"
                    , recID = 1
                    , templateID = 1 }
            )
        , new AjaxOptions
            {
                HttpMethod="POST"
                , LoadingElementId="Refresh"
            })%>

是否存在阻止AJAX返回文件类型的固有限制,或者是否错过了正确的搜索组合以找到明显的答案?

1 个答案:

答案 0 :(得分:0)

我不确定我理解你在谈论什么。您是否尝试将文件内容返回到javascript变量?这是我唯一可以想象的“AJAX RouteLink”。如果您希望它提示用户打开或保存,请使用普通链接。如果您尝试在页面中嵌入文件,请不要返回文件,返回用于嵌入的html。

相关问题