LCJ
LCJ

Reputation: 22652

ASP.NET MVC3: Default value selection in Dropdown

I have a model named Program. Each program will have a telecast schedule as described below.

enum SchduleEnum { Daily = 0, Weekly, Monthly };

Each program can have a category like “News” , “Movie”, “Discussion”.

In the Program Scheduling view, users must be able to select the schedule from a dropdown. However, there should be default values in the schedule dropdown. The rule is that the default schedule should be “Daily” if it is “news” category. The default schedule should be “Weekly” if the category is “Movie”. The default schedule should be “Monthly” if category is “Discussion”.

I have the following code which shows blank as default value in schedule dropdown. How do we modify the code to show required default values based on the rules defined above?

Based on MVC principle: The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model.

  1. How do we achieve it in quick way?

  2. How do we achieve it standard way (following MVC principle listed above)

CODE

public class Program
{
    public int ProgramID { get; set; }
    public string ProgramName { get; set; }
    public int ScheduleID { get; set; }
    public string ProgramCategory { get; set; }
}

CONTROLLER

namespace MyDefaultValueTEST.Controllers
{
public class MyProgramController : Controller
{
    enum SchduleEnum { Daily = 0, Weekly, Monthly };
    List<Program> programList = new List<Program>()
                          {
                            new Program
                            {
                                ProgramID = 1,ProgramName = "Program1",
                                ProgramCategory = "News"
                            },
                            new Program
                            {
                                ProgramID = 2,ProgramName = "Program2",
                                ProgramCategory = "Movie"
                            },
                            new Program
                            {
                                ProgramID = 3,ProgramName = "Program3",
                                ProgramCategory = "Discussion"
                            }

                          };



    public ActionResult ScheduleProgram()
    {
        ViewBag.ScheudleEnum = GetSchduleSelectList();
        return View(programList);
    }

    public static SelectList GetSchduleSelectList()
    {
        Array values = Enum.GetValues(typeof(SchduleEnum));
        List<System.Web.UI.WebControls.ListItem> items = new List<System.Web.UI.WebControls.ListItem>(values.Length);

        foreach (var i in values)
        {
            items.Add(new System.Web.UI.WebControls.ListItem
                    {
                        Text = Enum.GetName(typeof(SchduleEnum), i),
                        Value = ((int)i).ToString()
                    }
                    );
        }

        return new SelectList(items);
    }


    }
}

VIEW

@model IEnumerable<MyDefaultValueTEST.Program>

@{
ViewBag.Title = "ScheduleProgram";
}

<h2>ScheduleProgram</h2>


@using (Html.BeginForm())
{
<table>
    <tr>
        <th style="border:1px solid Teal; background-color:Gray">
            ProgramName
        </th>
        <th style="border:1px solid Teal; background-color:Gray">
            ProgramCategory
        </th>
        <th style="border:1px solid Teal; background-color:Gray">  </th>
    </tr>

    @Html.EditorForModel()

</table>

<p>
    <input type="submit" value="Save Schedules" />
</p>
}

EDITOR TEMPLATE(Program.cshtml)

@model MyDefaultValueTEST.Program
<tr>
<td style="border:1px solid Teal">
    @Html.EditorFor(x => x.ProgramName)
</td>
<td style="border:1px solid Teal">
    @Html.EditorFor(x => x.ProgramCategory)
</td>
<td style="border:1px solid Teal">
    @Html.DropDownListFor(x => x.ScheduleID, (SelectList)ViewBag.ScheudleEnum, String.Empty)
</td>
<td>
    @Html.HiddenFor(x => x.ProgramID)
</td>

</tr>

READING

  1. C# mvc 3 using selectlist with selected value in view

  2. dropdownlist set selected value in MVC3 Razor

  3. MVC 3 Layout Page, Razor Template, and DropdownList

  4. DropdownListFor default value

  5. Html.dropdownlist not retaining the selected value

  6. Getting values from an asp.net mvc dropdownlist

  7. ASP.NET MVC ViewModel and DropDownList

  8. dropdown value null when using, viewmodel & modelbinder in asp.net mvc

  9. Support for optgroup in dropdownlist .NET MVC?

Upvotes: 3

Views: 4655

Answers (1)

Manas
Manas

Reputation: 2542

You can declare your model as

public class TestModel
{
    public SchduleEnum SelectedScheduleEnum { get; set; }
    public ProgramCatagory SelectedProgram { get; set; }

    public IEnumerable<SelectListItem> ScheduleEnums
    {
        get { return this.GetScheduleEnums(); }
    }

    public IEnumerable<SelectListItem> SelectedPrograms
    {
        get { return this.GetSelectedPrograms(); }
    }

    private IEnumerable<SelectListItem> GetSelectedPrograms()
    {
        List<SelectListItem> items=new List<SelectListItem>();
        Enum.GetNames(typeof(ProgramCatagory)).ToList().ForEach(s=>{
            bool IsSelected=((int)Enum.Parse(typeof(ProgramCatagory), s)).Equals((int)SelectedScheduleEnum);
            if(IsSelected)
                this.SelectedProgram = (ProgramCatagory)Enum.Parse(typeof(ProgramCatagory), s);
            items.Add(new SelectListItem()
                {
                    Text = s,
                    Value = s,
                    Selected = IsSelected
                });
        });
        return items;
    }

    private IEnumerable<SelectListItem> GetScheduleEnums()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        Enum.GetNames(typeof(SchduleEnum)).ToList().ForEach(s =>
        {
            bool IsSelected = ((int)Enum.Parse(typeof(SchduleEnum),s)).Equals((int)SelectedProgram);
            if (IsSelected)
                this.SelectedScheduleEnum = (SchduleEnum)Enum.Parse(typeof(SchduleEnum), s);
            items.Add(new SelectListItem()
            {
                Text = s,
                Value = s,
                Selected = IsSelected
            });
        });
        return items;
    }

}
public enum SchduleEnum {
    Daily = 0, 
    Weekly,
    Monthly 
};
public enum ProgramCatagory
{
    News=0 ,
    Movie,
    Discussion
};

In The controller,

public ActionResult Index()
    {

        TestModel model = new TestModel();
        model.SelectedScheduleEnum = SchduleEnum.Monthly;
        return View(model);
    }

In the view you can call like,

<%:Html.DropDownListFor(m=>m.SelectedProgram,Model.SelectedPrograms)%>
<%:Html.DropDownListFor(m=>m.SelectedScheduleEnum,Model.ScheduleEnums) %>

Upvotes: 1

Related Questions