gpt4 book ai didi

c# - 如何在 ASP.NET MVC Controller 中使用可选参数

转载 作者:IT王子 更新时间:2023-10-29 03:58:02 25 4
gpt4 key购买 nike

我在链接到两个列表的 View 上有一组下拉控件。

//control
ViewData["Countries"] = new SelectList(x.getCountries().ToList(), "key","value",country);
ViewData["Regions"] = new SelectList(x.getRegions(country).ToList(), "id", "name", regions);

/*
on the view
*/

<% using (Html.BeginForm("","", FormMethod.Get))
{ %>
<ol>
<li>
<%= MvcEasyA.Helpers.LabelHelper.Label("Country", "Country:")%>
<%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>
<input type="submit" value="countryGO" class="ddabtns" />
</li>
<li>
<%= MvcEasyA.Helpers.LabelHelper.Label("Regions", "Regions:")%>
<%= Html.DropDownList("Regions", ViewData["Regions"] as SelectList,"-- Select One --") %>
<input type="submit" value="regionsGO" class="ddabtns" />
</li>
</ol>
<br />
<input type="submit" value="go" />
<% } %>

因此它向同一页面发送查询(因为它只是真正提供设置/更新适当下拉菜单的替代方法,这是可以接受的,因为它将全部替换为 javascript)。

点击时的 url 类似于...

http://localhost:1689/?country=FRA&regions=117

区域取决于国家代码。

我试图在不考虑路由的情况下实现这一点,因为这个功能没有实际意义。

所以Controller有下面的方法。

public ActionResult Index(string country, int regions)

最佳答案

字符串应该没问题,因为它会作为空字符串传递。对于 int,使其可为空:

public ActionResult Index(string Country, int? Regions)

此外,您会注意到我将其大写,与您的查询字符串相同。

编辑

请注意,ASP.NET 现在允许您定义默认参数。例如:

public ActionResult Index(string Country, int Regions = 2)

但是,恕我直言,我建议您只在语义有意义的地方使用默认值。例如,如果 Regions 参数的目的是设置一个国家/地区的区域数,而大多数国家/地区有 2 个区域(北部和南部),那么设置默认值是有意义的。我不会使用表示缺少输入的“魔数(Magic Number)”(例如 999 或 -1)——此时您应该只使用 null

关于c# - 如何在 ASP.NET MVC Controller 中使用可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1119849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com