2017-01-09 218 views
-1

我想重定向到控制器功能中的另一個視圖。返回視圖無法正常工作

這裏是我的代碼 鑑於:

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

回答

3

首先,如果您使用內容類型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

什麼意思,不工作?任何錯誤?任何細節? 請提供任何有用的東西,以便我可以幫助你:) –