提交表单是返回application / json而不是text / html

时间:2013-12-30 18:38:16

标签: c# jquery asp.net-mvc razor content-type

我已使用以下内容更改了提交提交:

<a style="text-decoration:none;" href="@Url.Action(item.ListAction, item.ListController, new { ids = string.Join("-", item.Ids), categoryId = item.Id, search = (string)ViewBag.Search, location = (string)ViewBag.Location })">

要:

@using(Html.BeginForm(null, null, FormMethod.Post, new { id = "homeCategoryForm" }))
{
    @Html.AntiForgeryToken()

    @Html.Hidden("ids")
    @Html.Hidden("categoryId")
    @Html.Hidden("search")
    @Html.Hidden("location")
}

使用JQuery提交:

$(document).on("click", ".innerelement", function (e)
{
    var elementId = e.target.id.split('_')[1];

    action = "/" + $("#controller_" + elementId).val() + "/" + $("#action_" + elementId).val();

    $("#homeCategoryForm").attr("action", action);
    $("#ids").val($("#ids_" + elementId).val());
    $("#categoryId").val($("#categoryId_" + elementId).val());
    $("#search").val($("#search_" + elementId).val());
    $("#location").val($("#location_" + elementId).val());

    $("#homeCategoryForm").submit();
});

控制器:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual ActionResult GetAllByIds(string ids, int categoryId, string search, string location)
{
    AdGetAllByCategoryListViewModel model = new AdGetAllByCategoryListViewModel();

    model.Ads = Mapper.Map<IList<AdGetAllByCategoryDto>, IList<AdGetAllByCategoryViewModel>>(_adService.GetAllByIds(ids));

    model.Category = Mapper.Map<CategoryDto, CategoryViewModel>(_categoryService.GetById(categoryId));

    return View(MVC.Ad.Views.GetAllByCategory, model);
}

问题是使用Form Post方法的View正在生成一个application / json View(Source)而不是text / html。

编辑:

视图是从PartialView渲染的,所以可能是问题吗?

我已经使用PartialView进行了测试,并且渲染了视图的HTML,但不是所有的布局视图。

知道为什么吗?

由于

1 个答案:

答案 0 :(得分:1)

我找到了问题:

在视图的布局中我有一个表格:

<!-- Comments form container -->
<div class="comentsform">

    <!-- Comments form -->
    @{ Html.RenderAction(MVC.Comment.Create()); }

</div>
<!-- Comments form container closed -->

控制器是:

public virtual PartialViewResult Create()
{
    return PartialView();
}

这里的问题是我还有一个JSON Action来发送jQuery的评论:

[HttpPost]
[ValidateAntiForgeryToken]
public virtual JsonResult Create(CommentViewModel commentViewModel)
{
    CommentDto comentDto = Mapper.Map<CommentViewModel, CommentDto>(commentViewModel);

    _commentService.Create(comentDto);

    commentViewModel.Result = HeelpResources.CommentViewModelResultMsgOk;

    return Json(commentViewModel);
}

所以看来,当布局呈现来自Form POST动作时,它会搜索Html.RenderAction在布局中呈现的所有[HttpPost]动作。

在这种情况下,因为我有一个带有JsonResult类型的[HttpPost] Action的Html.RenderAction,所有结果View都会在JSON响应中转换。

所以现在,我唯一需要做的就是将JSON Action的名称更改为公共虚拟JsonResult CreateSend,例如,解决问题!

再次感谢所有人的帮助。