【问题标题】:fill html.textbox upon html.dropdownlist onchange in asp.net mvc在asp.net mvc中的html.dropdownlist onchange上填充html.textbox
【发布时间】:2010-07-16 17:38:52
【问题描述】:

我是 asp.net mvc 的新手...并且需要帮助解决以下问题:

当表单加载时,我的 Country 下拉列表有一些值。我希望当用户从下拉列表中选择一个值时,它应该返回到控制器并调用数据库以根据所选国家/地区检索 CountryCode 值。如何模拟回发调用?

提前致谢

深度

【问题讨论】:

    标签: c# asp.net-mvc-2


    【解决方案1】:

    与 ASP.NET MVC 中的经典 WebForms 不同,没有 PostBack 这样的概念。因此,首先您需要一个模型来表示您的数据:

    public class MyViewModel
    {
        public string SelectedCountry { get; set; }
        public IEnumerable<SelectListItem> Countries { get; set; }
    }
    

    然后你将需要一个控制器来定义两个动作:一个用于呈现表单,另一个用于处理提交:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel
            {
                // you probably would fetch those from the database
                Countries = new SelectList(new[] 
                {
                    new { Value = "FR", Text = "France" },
                    new { Value = "US", Text = "USA" } 
                }, "Value", "Text")
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(string selectedCountry)
        {
            // selectedCountry will contain the code that you could use to 
            // query your database
            return RedirectToAction("index");
        }
    }
    

    最后,您可能会向将包含标记的模型抛出一个强类型视图:

    <% using (Html.BeginForm()) { %>
        <%: Html.DropDownListFor(x => x.SelectedCountry, Model.Countries) %>
        <input type="submit" name="OK" />
    <% } %>
    

    如果这对你没有任何意义,我建议你reading the getting started tutorials

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      您需要在您的 asp 下拉菜单中设置 AutoPostBack="true"。此外,您的控件需要设置您的 OnSelectedIndexChanged="SomeFunction"。每当您的下拉列表中的索引发生更改时,这将在您的代码隐藏中调用一个函数。这是一个例子

      <asp:DropDownList ID="dropDownID" runat="server" AutoPostBack="true" OnSelectedIndexChanged="OnDropdownIndex_Change"> </asp:DropDownList>

      【讨论】:

      • 问题是关于 ASP.NET MVC 而不是 Web 窗体。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多