使用按钮将选定的下拉值传递给控制器 [英] Pass Selected Dropdown Value to Controller using a Button

查看:90
本文介绍了使用按钮将选定的下拉值传递给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,单击按钮时,下拉列表中选择的值应传递给控制器​​,但不能传递给控制器​​。如何传递值?

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?

视图:

@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>
....

型号:

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

    public SelectList Companies { get; set; }    
}


推荐答案

您的链接正在使用剃刀指定路由 id 值的代码,它是服务器端代码。

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.

要么使用生成GET并提交选项值的表单

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>

请注意,这将生成带有 id的查询字符串值的url ,而不是路由值(即它将生成 ../ Invoice / Create?id = 1 ,而不是..。 / Invoice / Create / 1

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

或者,您可以使用javascript / jquery通过基于所选选项构建网址来进行重定向

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();
}

这篇关于使用按钮将选定的下拉值传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆