返回视图无法正常工作

问题描述:

我想重定向到控制器功能中的另一个视图。返回视图无法正常工作

这里是我的代码 鉴于:

$.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

您是否设置了断点,调试了您的代码并进行了验证,它是否被调用并正在工作? – Marco

+2

你的HTTP请求由'CreateEBulletinPdf()'调度,它不返回任何东西('void')。在内部,它确实调用'ProductsEBulletin()'(返回'ActionResult'),但是'CreateEBulletinPdf'不会对它做任何事情。 – haim770

+0

@Marco,是的,我调试我的代码一切正常.. – cagin

首先,如果您使用内容类型contentType: "JSON"拨打ajax,则不需要像在此处data: JSON.stringify({ "productIdList": selectedProductIdList }),那样对数据对象进行串联。而且因为你期待得到HTML作为回报,你需要指定dataType: 'html'

其次,你的CreateEBulletinPdf方法没有返回值因此与return ProductsEBulletin();取代的最后一条语句。

最后,您调用从阿贾克斯行动将无法正常工作的方式,你需要的JsonResult代替ActionResult动作结果返回纯HTML,然后它的的success功能插入到你的HTMLajax,因为这样:

行动代码:

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(); 
    } 
} 

Javascript代码:

$.ajax({ 
    type: "POST", 
    url: '@Url.Action("CreateEBulletinPdf","EBulletin")', 
    contentType: "application/json", // type of data sent to server 
    dataType: "html", // type of data received from server 
    data: { "productIdList": selectedProductIdList }, 
    success: function (result) { 
      $('#selector-of-tag-to-be-filled').html(result); 
    } 
}); 
+0

你的答案更全面 – BWA

+0

感谢你的回答,我根据你的建议改变了我的代码。 – cagin

+0

什么意思,不工作?任何错误?任何细节? 请提供任何有用的东西,以便我可以帮助你:) –