Reputation: 575
I have a strange problem. I have a link on my Product details view which has to navigate to the Purchase page.
If I use this link it navigates to the desired page
<a href="@Url.Action("PurchaseProduct", "Purchase", new { id = Model.ID, name = Model.Name})" id="link">
Buy
</a>
But I need the quantity info, so I had to resolve this via javascript to send to the controller the quantity as parameter
I tried in many ways:
<a href="#" id="link" onclick="return test();">
Buy
</a>
<a href="javascript:test();">More >>></a>
And this is my javascript code:
<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>
With this javascript code it enters on the controller method, but the strange thing is that it does nothing. Doesn't goes to the PurcahseProduct page, remain on the details page. This is my controller:
As I said if I use this link it navigates to the PurchaseProduct page.
Do you have any idea what I do wrong? what can cause this strange behavior?
Upvotes: 0
Views: 36
Reputation: 525
It behaves the way you describe because you use ajax to post data to the server. So you can either redirect manually to the desired page in your $ajax.success callback or use proper form to submit data without 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>
}
Upvotes: 1