0
votes

I am so confused how to make the dropdownlist to show the selected value.

Model:

public class SampleModel
{        
    public string State { get; set; }
}

Controller:

public ActionResult EditInformation()
{
    ViewBag.State = new SelectList(db.States, "StateName", "StateName");

    string userEmail = User.Identity.GetUserName();

    Sample model = new SampleModel();     
    model.State = "Melbourne";

    return View(model);
}

View :

@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")

The list is showing the states just fine, but it doesn't automatically select the value I assigned ("Melbourne"). I have tried using the selectlist constructor to assign the selectedValue, but after doing a lot of research, someone wrote that it is redundant to use the selectlist constructor if you are using Html.DropdownListFor() since you will be using the value assigned to the model.

EDIT:

Here is my db.State model:

public class State
{
    [Key]
    public int StateId { get; set; }
    public string StateName { get; set; }

}

Again to clarify, I want to use StateName as the value and the text for the selectlistitem.

EDIT: My full action method:

public ActionResult EditInformation()
    {
        //var states = ndb.States.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateName , Selected = s.StateName == "Jawa Timur" }).ToList();

        ViewBag.State = new SelectList(ndb.States, "StateName", "StateName");
        ViewBag.City = new SelectList(ndb.Cities, "CityName", "CityName");
        string[] countries = { "Indonesia" };
        ViewBag.Country = new SelectList(countries);

        string userEmail = User.Identity.GetUserName();
        try
        {
            UserInformation userInfo = ndb.UserInformations.Single(m => m.Email == userEmail);
            UserAccountViewModel model = new UserAccountViewModel();

            model.Address = userInfo.Address;
            model.Email = userEmail;
            model.FirstName = userInfo.FirstName;
            model.LastName = userInfo.LastName;
            model.Phone = userInfo.Phone;
            model.PostalCode = userInfo.PostalCode;
            Debug.Print(userInfo.State);
            model.State = userInfo.State;
            model.City = userInfo.City;
            model.Country = userInfo.Country;


            return View(model);
        }catch { }
        return View();

    }
3
What is your db.States look like? - SᴇM
why did you post a model of SampleModel then stuff your ViewBag with something from db.States? Post your model for States. Does your db.States have an ID? - Grizzly
@BviLLe_Kid, actually there is more to the model, I just simplify it so you guys can read better, the rest is just simple property and they are working as expected. my db.States have an ID, but i prefer using the name as the value. - Stewart Jingga

3 Answers

1
votes
public ActionResult EditInformation(int? id /*this will be passed from your route values in your view*/)
{
    State myState = db.States.Find(id)


    ViewBag.State = new SelectList(ndb.States, "StateId", "StateName", myState.StateId);
}//I only added this because this is what the question pertains to.

In your EditInformation View you need to have an actionlink to link to the user's id so that you pull up the right information, so:

EditInformation View:

@foreach (var item in Model)
{
    @Html.ActionLink("Edit Information", "EditInformation", /*Controller Name if this view is rendered from a different controller*/, new { id = item.id })
}
0
votes

try this:

public class SampleModel
{        
    public int Id { get; set; }
    public string State { get; set; }
}

Controller:

public ActionResult EditInformation()
{
    //Select default value like this (of course if your db.States have an Id):
    ViewBag.State = new SelectList(db.States, "Id", "StateName", 1 /*Default Value Id or Text*/);
    . . .
    return View();
}

SelectList(IEnumerable, String, String, Object) - Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.

View:

@Html.DropdownList("State", null, "-- Select State --")

Or Like you do:

@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")

UPDATE:

You can get Selected text using jQuery like so: Add @Html.HiddenFor(x => x.State)

@Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --", new { id = "stateId" })
@Html.HiddenFor(x => x.State)

JS:

$(function () {
$("form").submit(function(){
    var selectedText= $("#stateId :selected").text();
    $("#State").val(selTypeText);           
  });
});

Post:

[HttpPost]
public void UploadDocument(State model)
{
   if(ModelState.IsValid)
   {
      string state = model.State;
   }
}
0
votes

OKAY, So after researching for quite some time, the problem lies in the naming convention. Apparently, you cannot use ViewBag.State for Html.DropdownListFor(m => m.State), this somehow causes the Html.DropdownListFor(m => m.State) to not reading the data properly.