2017-02-28 21 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

相关问题