2017-05-30 173 views
0

當點擊「a」錨標記我想從一個控制器(HomeController.cs)重定向到另一個控制器(CartController.cs)索引[GET]並執行代碼並返回數據到視圖(車/ index.cshtml)。無法呈現按鈕點擊視圖

這裏是js代碼

$(document).on('click', '.btn-margin', function() { 
     if (parseInt($('#UserID').val()) > 0) { 
      var pmID = $(this).attr("id"), 
       bid = $(this).attr("brand-id"); 
      $.ajax({ 
       url: '@Url.Action("index", "cart")', 
       data: { "id": pmID, "bid" : bid }, 
       type: 'GET', 
       dataType: 'json', 
       success: function (response) { 

       }, 
       error: function (xhr, status, error) { 
       } 
      }); 
     }   
    }); 

和CartController

[HttpGet] 
public ActionResult Index(long id = 0, long bid = 0) 
{ 
    GetStates(); 
    return View(productBL.GetProductById(id, bid)); 
} 

正如預期的那樣具有重定向到的車index.cshtml ..但我的結果仍然在指數的HomeController。 cshtml頁面。

請幫我如何獲得預期的結果..

+0

您是否嘗試添加返回RedirectToAction(「Index」,「CartController」);在你的家庭控制器? – ISHIDA

+0

我需要將參數傳遞給該動作 – thiru

+0

試試這個 - 返回RedirectToAction(「Index」,「CartController」,new {id:pmId}) – ISHIDA

回答

0

你不需要Ajax調用此。 on you'a'點擊使用類似這樣的東西

$('.btn-margin').on('click',function(){ 
if (parseInt($('#UserID').val()) > 0) { 
      var pmID = $(this).attr("id"), 
      var bid = $(this).attr("brand-id"); 
      window.location.href = "/cart/index?id="+pmID+"&bid=" +bid; 
      } 
} 

希望這會有所幫助。

+0

這顯示了url中的參數..我試圖通過ajax-call來避免這.. .. @ karthik – thiru

+0

@thiru如果你有類或id容器在你的視圖呈現..然後成功,你可以做到這一點$(「id或類的容器」)。html(響應) –

0

在你的AJAX調用,你定義了這個:

$.ajax({ 
     dataType: 'json', 

但是你的控制器動作返回HTML,而不是JSON:

public ActionResult Index(long id = 0, long bid = 0) 
    return View(productBL.GetProductById(id, bid)); 

它應該返回使用JSON方法的數據:

return Json(prodcutBL.GetProductById(id, bid), JsonBehavior.AllowGet); 

第二個參數表示允許GET請求(通常POST只是必需的,否則woul d拋出異常)。這將返回一個JSON對象到成功回調,然後你可以像正常一樣訪問數據。您可能要直接返回一個對象,而不是數組,如:

return Json(new { products = prodcutBL.GetProductById(id, bid) }, JsonBehavior.AllowGet); 

,然後在回調訪問它想:

success: function (response) { 
    if (response.products.length == 0) 
     alert("No data available"); 
    else /* do something */ 
      }, 

Microsoft建議returning an object, not an array, for a web response.

0

試試這個 - return RedirectToAction("Index", "CartController", new{ id: pmId})