返回ContentResult for Ajax Response在.NET MVC控制器中有额外的标签

时间:2010-11-05 19:10:14

标签: .net asp.net-mvc asp.net-mvc-2

我有一个Controller Action试图将纯文本返回给AJAX调用。 E.G .-

[HttpPost]
public ActionResult SubmitAttachment(int id, HttpPostedFileBase theFile){
...
...
   return Content("Success");
}

在我正在进行ajax调用的javascript函数中,我希望响应文本只是“成功”,但我得到的是"<head></head><body>Success</body>"

在99%的其他控制器操作中,我没有这个问题。我唯一能想到的就是这个因为AJAX对“SubmitAttachment”的调用是一个带有“enctype = multipart / form-data”的表单POST,其他的AJAX调用没有上传任何文件。

之前有没有遇到过这个?如果是这样......我怎么才能让它返回纯文本?

注意:我还尝试了return Content("Success", "text/plain"),但只是在“成功”字符串周围添加了额外的<pre></pre>标记。

2 个答案:

答案 0 :(得分:2)

无法重现此行为:

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(int id, HttpPostedFileBase theFile)
    {
        return Content("Success", "text/plain");
    }
}

查看:

<script type="text/javascript" src="<%: Url.Content("~/scripts/jquery-1.4.1.js") %>"></script>
<script type="text/javascript">
    $(function () {
        $('form').submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    alert(result);
                }
            });
            return false;
        });
    });
</script>

<form action="/" method="post" enctype="multipart/form-data">
    <input type="text" name="id" value="4" />
    <input type="submit" value="OK" />
</form>

提交表单后,服务器仅返回"Success"

答案 1 :(得分:1)

我会做bzlm所建议的,使用fiddler测试它以确保那些标签实际上以这种方式返回。如果它们仍然存在,请尝试返回纯字符串。将返回类型设置为string,然后返回“success”而不使用Content()。如果你在返回一个字符串时仍然在它周围获得标签,那么你处于另一个现实中,在那里不可能的事情是可能的。