简体   繁体   中英

Pass Selected Dropdown Value to Controller using a Button

In the example below when clicking the button the value selected in the dropdownlist should be passed to the controller, but its not. How can I pass the value?

View:

@model BillingModel
...
<select id="ddl" asp-for="SelectedCompanyID" asp-items="Model.Companies" class="form-control"></select>

<a asp-action="Create" asp-controller="Invoice" asp-route-id="@Model.SelectedCompanyID" class="btn btn-primary btn-sm"></span> Create Invoice</a>
....

Model:

public class BillingModel
{
    public int SelectedCompanyID { get; set; }       

    public SelectList Companies { get; set; }    
}

Your link is using razor code to specify the route id value which is server side code. It does not change on the client side just because a option is selected.

Either use a form that makes a GET and submits the option value

<form asp-controller="Invoice" asp-action="Create" method="get">
    <select id="ddl" asp-for="SelectedCompanyID" asp-items="Model.Companies" class="form-control"></select>
    <input type="submit" value="Create Invoice" /> // you can style this to look like your link if you want
</form>

Note that this will generate the url with a query string value for the id , not a route value (ie it will generate ../Invoice/Create?id=1 , not ../Invoice/Create/1 )

Alternatively, you could use javascript/jquery to make the redirect by building a url based on the selected option

<a id="create" href="#" class="btn btn-primary btn-sm">Create Invoice</a>

$('#create').click(function() {
    var baseUrl = '@Url.Action("Create", "Invoice")';
    location.href = baseUrl + '/' + $('#SelectedCompanyID').val();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM