简体   繁体   中英

fill html.textbox upon html.dropdownlist onchange in asp.net mvc

I'm new to asp.net mvc... & need help for my below question:

When the form loads my Country dropdownlist has some values. I want when the user selects a value from the dropdown list it should go back to the controller and makes a call to the database to retrive the CountryCode value based on the Country selected. How do I simulate that postback call?

Thanks in Advance

Deepthi

Contrary to classic WebForms in ASP.NET MVC there's no such notion as PostBack. So to begin with you need a model that is going to represent your data:

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

Then you are going to need a controller which defines two actions: one for rendering the form and another handling the submission:

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

And finally you might throw a strongly typed view to the model that will contain the markup:

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

If nothing of this make any sense to you, I would suggest you reading the getting started tutorials .

You need to set AutoPostBack="true" in your asp dropdown. Also your control needs to set your OnSelectedIndexChanged="SomeFunction". This will call a function in your codebehind whenever the index in your dropdown is changed. Here's an example

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

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