views:

186

answers:

3

Hi Guys,

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

A: 

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>

jgroat
The question is about ASP.NET MVC not about Web Forms.
Deependra Solanky
+1  A: 

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.

Darin Dimitrov