views:

367

answers:

1

I have Dropdown and on click of a button, I want to display data in the usercontrol the below code is not working as expected.

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%
        using (Html.BeginForm())
        {%>
    <%=Html.DropDownList("CarMake", (SelectList)ViewData["CarMake"])%>
    <input type="submit" value="Get all car model" />
    <%
         Html.RenderPartial("CarModel");
        } %>
</asp:Content>

// in controller

 public ActionResult Test1()
        {
            ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Test1(int carMake)
        {
            ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
            var carModel = _carDataContext.Models.Where(m => m.MakeId == carMake).ToList();
            return PartialView("CarModel", carModel);
        }
A: 

Since you're doing a full post of the form, you don't want to return a partial view. You want to set the ViewData["CarModel"] to the correct model, then re-render the same view. The RenderPartial in the view will use this to "include" the correct partial view in the code.

Note this would be different if you were posting via AJAX. At that point, you'd have it set up to replace a particular element of the page and you would want to only render the partial that goes into that element.

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Test1(int carMake)
    {
        ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
        ViewData["CarModel"] = _carDataContext.Models.Where(m => m.MakeId == carMake).ToList();
        return View();
    }
tvanfosson