Create hyperlink (anchor tag) in MVC to send data to controller
I have a fairly simple scenario
I have an action method in my controller with syntax like
[HttpPost]
public ActionResult Consignment(string txtConsNo, string isReferenceTracking)
{}
Not on a page, I need to create a hyperlink in the application that needs to access this action method. I am using HTML.ActionLink method to create hyperlink such as
@Html.ActionLink((string)item.RDC_CONSNO, "Consignment", "Tracking", new { txtConsNo = (string)item.RDC_CONSNO, rdbConsNo = "" }, null)
But it creates a link like this
http://localhost:3412/Tracking/Consignment?txtConsNo=100245506
How do I get around this?
thank
source to share
I am assuming you are using item
instead of the model that you are rendering in the loop? Anyway, I would suggest adding a form and a link to it; the link (s) will look like this:
@Html.ActionLink(
(string)item.RDC_CONSNO,
"Consignment",
"Tracking",
new { @class = "consignmentLink" });
... then after the loop (if any) you put in the form and some pluggable JavaScript, like this:
@using (Html.BeginForm("Consignment", "Tracking"))
{
@:<input type="hidden" id="txtConsNo" name="txtConsNo" />
}
$("a.consignmentLink").click(function(e) {
e.preventDefault();
var $consignmentNumberInput = $("#txtConsNo");
$consignmentNumberInput.val($(this).text());
$consignmentNumberInput[0].form.submit();
});
To populate your action parameter isReferenceTracking
, you can add another hidden field and have that value as a data attribute for each link.
source to share
I think you have two options.
- Remove attribute
[HttpPost]
(preferred in my opinion) - Use jquery to post: $ .post ()
Here's how to do a jQuery approach (if needed)
Html:
<a href="#" class="postToConsignment"
data-consno="@item.RDC_CONSNO">@item.RDC_CONSNO.ToString()</a>
javascript (which should be in your view):
$(function(){
$('.postToConsignment').on('click', function(e){
// Stop links normal behaviour
e.preventDefault();
//Get the url to post to
var url = '@Url.Action("Consignment", "Controller")';
//Get consNo
var consNo = $(this.data('consno');
$.post(url, new { txtConsNo: consNo}, function(data) {
//Deal with the result (i.e. the data param)
});
});
});
source to share
Also you can use button:
for example in core asp syntax:
//some other tags
<form method="post">
<input asp-for="YourModelPropertyOrYourMethodInputName"
value="@TheValue" type="hidden" />
<button type="submit" class="link-button" formaction="/TheDestinationController/TheDestinationActionMethod">
@(TextValue)
</button>
</form>
source to share