Manny Sran
Manny Sran

Reputation: 173

Set default for dropdownlist that has been populated by database information. MVC 4

Hi there I have a program that reads from a database table to populate a dropdownlist.

Type Table:

id     type
1      Day
2      Month
3      Year

Model:

[Display(Name = "Type: "),
Required(ErrorMessage = "Required")]
public int type { get; set; }

Controller:

    public void loadDropDown()
    {
         reviewlogsEntities db = new reviewlogsEntities();
         IEnumerable<SelectListItem> type = db.types.Select(m => new SelectListItem
         {
            Value = SqlFunctions.StringConvert((double)m.id),               
            Text = m.type1
         });

         ViewBag.type = type;
     }

        [HttpGet]
        public ActionResult AddLogReview()
        {
            if (Request.IsAuthenticated)
            {
                loadDropDown();        
                return View();
            }                             
            else
            {
                return RedirectToAction("index", "home");
            }
        }

        [HttpPost]
        public ActionResult AddLogReview(AddLogModel LogSubmission)
        {
            loadDropDown();

             if (ModelState.IsValid)
             {
                 //Send Data to database
                 return View();
             }
             else
             {
                 //If not authenticated then display an error message
                 ModelState.AddModelError("", "Submission erorr");       
             }
              return View();
        }

View:

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.type)
    @Html.DropDownList("type", ViewBag.type as IEnumerable<SelectListItem>, new { onchange = "setDisplay();"})

    <input class="submitButton" type="submit" value="Log In" style="margin-left:126px;margin-bottom: 20px;" />
}

I am using the same form on 3 different pages, one page is day, month and, year. So the dropdownlist should default to day, month, or year on their respective links.

My first idea was to use javascript to set the default value onload. However, the problem is, if they click on the day page they can still do a month log as well. Thats not a problem until you realize that because onload is called. If they make any errors on the page. It will default back to the default value. So for example the user goes to day logs, but then realizes they want to do a month log they change the dropdown to month log, however the user forgets to fill in a textbox that was required and when they submit it now it will show the required boxes that don't have a value. At that time it will default back to day logs and if they fill in the rest of the form and submit it they might not realize it was a day log instead of a month log.

So my question is how can I set it to a default value only when the page is loaded but not when the page is submitted/POST.

Upvotes: 0

Views: 77

Answers (1)

Szer
Szer

Reputation: 3476

Assume you have some Model with ListOfItems and you want ItemId be your drop down value and Name as drop down text:

@using (Html.BeginForm())
{
    @Html.CreateDropDownList(Model.ListOfItems, "DropDownListOfItems",
                             Model.ListOfItems.First(), "ItemId", "Name")
}

Model.ListOfItems.First() is where you select your default value

Added: and here is a vital part of answer:

using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class Extensions
{
    public static MvcHtmlString CreateDropDownList<T>(this HtmlHelper helper, IEnumerable<T> list, string name,
        T selectedT, string dataValue, string dataText)

    {
        return helper.DropDownList(name, new SelectList(list, dataValue, dataText, selectedT));
    }
}

Added2: To prevent problems with POST you should also populate form with your dropdownlist values so it should fill properly after POST.

Add this code somewhere before @Html.CreateDropDownList :

@for (var i = 0; i < Model.ListOfItems.Count; i++)
{
    @Html.HiddenFor(model => model.ListOfItems[i].ItemId)
    @Html.HiddenFor(model => model.ListOfItems[i].Name)
}

Upvotes: 1

Related Questions