开发者

Populating a dropdown list based on value selected in previous list (asp.net mvc3)

I'm trying to progam a strongly typed "Create" view using MVC 3 and razor. I want the user to be able to select a customer from a dropdown list (I populated this from my database using ViewBag in the controller). When the user has selected a customer I want a separate dropdown list to generate a list of dogs belonging to that customer related by the customerID in the database. The create button on the form will then take both of these values along with the the other fields and save it to the 开发者_如何学运维database.

Any help is greatly appreciated


I'll reference Darin's answer and add what you need here, only since you don't need exactly what he provided. However, the jQuery setup is exactly what you're looking for.

Add a View Model that contains the customer properties and dog ID.

public class CustomerDogCreateViewModel
{
    public string customerFirstName { get; set; }
    public string customerLastName { get; set; }
    // ... more properties from your ViewBag here
    public int dogID { get; set; }

    public CustomerDogCreateViewModel() { }
}

You'll only need one Controller action that returns JSON for the partial postback and populating of the "Dogs" dropdown.

public ActionResult Dogs(int customerID)
{
    // this is pseudo-LINQ, if you need help with your query,
    // we will need to know a little more about your data objects
    var dogs = // get dogs from your db
    select new
    {
        Id = dog.ID,
        Text = "Fido"
    };

    return Json(dogs, JsonRequestBehavior.AllowGet);
}

For your extra customer data, add these values as hidden inputs inside your create form

<form action="/YourController/Create" method="POST" >
    <!-- select lists -->
    <input type="hidden" name="customerFirstName" value="@ViewBag.customerFirstName" />
    <input type="hidden" name="customerLastName" value="@ViewBag.customerLastName" />
    <input type="submit" value="Create" />
</form>

And you can identically wire it up per Darin's response. One thing to mention; in my answer, only the Dog's ID attribute will post, so once the request is server-side, you'll need to retrieve that object and persist to your db however your business logic makes sense.

[HttpPost]
public ActionResult Create(CustomerDogCreateViewModel vm)
{
    var dog = YourDb.Dogs.Where(d => d.ID == vm.dogID).SingleOrDefault();
    // you didn't identify your data objects, so persist these to your db as usual.
    return View("CreateSuccess");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜