2017-02-28 22 views
0

我有一個奇怪的問題。 我的產品詳細信息視圖中有一個鏈接,它必須導航到採購頁面。Javascript代碼不把我帶到所需的控制器MVC

如果我使用這個鏈接它定位到所需的頁面

<a href="@Url.Action("PurchaseProduct", "Purchase", new { id = Model.ID, name = Model.Name})" id="link"> 
    Buy 
</a> 

但我需要的數量信息,所以我不得不通過JavaScript來解決這個發送到控制器的數量爲參數

我試圖在許多方面:

<a href="#" id="link" onclick="return test();"> 
    Buy 
    </a> 
<a href="javascript:test();">More >>></a> 

,這是我的javascript代碼:

<script> 
function test() { 
    var UrlSettings = { 
     url: '@Url.Action("PurchaseProduct", "Purchase")' 
    } 
    var selectedId = @Model.ID; 
    var selectedName = $('#name').val(); 
    var quantity = $('#quantity').val(); 

$.ajax({ 
    url: UrlSettings.url, 
    data: { 'id' : selectedId, 'name' : selectedName, 'quantity' : quantity }, 
    type: "post", 
    cache: false, 
    success: function (savingStatus) { 
     // $("#hdnOrigComments").val($('#txtComments').val()); 
     // $('#lblCommentsNotification').text(savingStatus); 
    }, 
    error: function (xhr, ajaxOptions, thrownError) { 
     //$('#lblCommentsNotification').text("Error encountered while saving the comments."); 
    } 
    }); 
}; 
</script> 

有了這個JavaScript代碼它進入控制器的方法,但奇怪的是,它什麼都沒做。不進入PurcahseProduct頁面,保留在詳細信息頁面上。 這是我的控制器:

enter image description here 正如我說,如果我用這個鏈接它導航到PurchaseProduct頁面。

你知道我做錯了嗎?什麼會導致這種奇怪的行爲?

+0

提交數據是否使用某種形式的框架?鏈接中的「@」符號是什麼? –

+0

爲什麼不使用表單將數量值發佈到控制器? –

回答

1

它的行爲與您描述的方式相同,因爲您使用ajax將數據發佈到服務器。所以,你可以手動重定向到所需的頁面在$ ajax.success回調或使用適當的形式沒有Ajax

@Html.BeginForm("PurchaseProduct", "Purchase", new { id = Model.ID, name = Model.Name }) 
{ 
    @Html.DropDownListFor(m => m.Name) 
    @Html.TextBoxFor(m => m.Quantity) 

    <button type="submit">submit</button> 
} 
+0

最後,我做了,就像你所建議的那樣,它的工作方式很好。謝謝 – Orsi

相關問題