返回视图无法正常工作

时间:2017-01-09 12:11:48

标签: c# ajax asp.net-mvc view

我想从控制器的功能重定向到另一个相同控制器的视图。

这是我的代码 在视图中:

$.ajax({
    type: "POST",
    url: '@Url.Action("CreateEBulletinPdf","EBulletin")',
    contentType: "application/json",
    dataType: "JSON",
    data: JSON.stringify({ "productIdList": selectedProductIdList }),
    success: function (result) {

    }
});

在控制器中:

public void CreateEBulletinPdf(string productIdList)
{             
    productIdList = productIdList.Substring(0, productIdList.Length - 1);

    var productIdStrings = productIdList.Split(',');

    detailViewModels = productIdStrings.Select(productIdString => PdfProduct(Convert.ToInt32(productIdString))).ToList();

    ProductsEBulletin();                             
}

public ActionResult ProductsEBulletin()
{
    try
    {
        return View(detailViewModels);
    }
    catch (Exception)
    {   
        throw;
    }
}

运行所有函数后,我的目标视图名称ProductsEBulletin未显示。我的错误在哪里?

1 个答案:

答案 0 :(得分:3)

首先,如果您使用内容类型ajax进行contentType: "JSON"调用,则无需像在此处data: JSON.stringify({ "productIdList": selectedProductIdList }),那样对数据对象进行字符串化。由于您希望获得HTML作为回报,因此您需要指定dataType: 'html'

其次,您的CreateEBulletinPdf方法未返回值,因此请将最后一个语句替换为return ProductsEBulletin();

最后,您从ajax调用操作的方式无法按预期工作,您需要JsonResult而不是ActionResult的操作结果才能返回纯HTML,然后将其插入HTML的{​​{1}}函数中的success,如下所示:

行动代码:

ajax

Javascript代码:

public JsonResult ProductsEBulletin()
{
    try
    {
        var data = RenderRazorViewToString("ProductsEBulletin", detailViewModels)
        return Json(data, JsonRequestBehavior.AllowGet);
    }
    catch (Exception)
    {
        throw;
    }
}

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}
相关问题