Build an ActionLink with a Value from the Page

Normally I would use an Html.BeginForm and wrap my link inside it to force it to the controller to handle any variables, but every so often you may need to add a link on the page which is populated with a variable from a textbox and you choose not to post back to the controller.


In this example I want to pass an account number in my ActionLink

So I start by adding the textbox on the page

 Enter Account Number: @Html.TextBox("account")

And the Actionlink (using some bootstrap formatting)

  @Html.ActionLink("View", "Customer", null, new { id = "View", @class="btn btn-danger" })
Then I handle the click event in script on the page
<script>
    $(function () {
        $('#View').click(function () {
            var fran = $('#account').val();
            this.href = this.href + '?id=' + encodeURIComponent(fran);
        });
    });

</script>
My link now resolves to something like this - had i indicated that id was part of the route it would resolve to Customer/Profile/MRR1212
/Customer/Profile?id=MRR1212

Alternatively if I wanted to populate my link with a value from a dropdown list I might have something like this
$(function () {$('#excel').click(function(e){
e.preventDefault();
if ($('#Concepts').val() == "0") {
$('#Message').text = 'Choose Concept';
}

window.location.replace =
'@Url.Action("StoreExtensionExcel", "Marketing")' + '?concept=' + $('#Concepts').val();
});

In this example I would have a button identified to the page by the name:
'<'input name="excel" type="button" value="Excel" '/>'
My dropdown looks like this:

@Html.DropDownList("Concepts", ViewData["Concepts"] as SelectList)


And when the excel button is clicked the click event is caught and the URL is changed including the value of the selected Concept

Comments

Popular posts from this blog

Linq Exclude from separate list

Sorting Ascending and Descending

Linq Query Syntax vs Method Syntax