1

I am a beginner in MVC and trying to bind drop-down list to a model using data from a database lookup table.

My Model:

 public class State
{
    [Required]
    public string StateName { get; set; }
    public int CountryId { get; set; }
    public List<SelectListItem> CountryList { get; set; }

}

In my Controller:

[HttpGet]
public ActionResult AddState()
{
    State obj = new State();
    using (MvcWorkEntities context = new MvcWorkEntities())
    {
        obj.CountryList = context.Mst_Country.ToList();
    }
    return View(obj);
}

The View:

@using(Html.BeginForm("AddState","Home",FormMethod.Post))
{ 
<div class="col-md-4">
    <div class="form-group">
        @Html.Label("Select Country")
      @Html.DropDownListFor(m=>m.CountryId,Model.CountryList);
    </div>
</div>
<div class="col-md-4">
    <div class="form-group">
        @Html.Label("Enter State Name")
        @Html.TextBoxFor(m=>m.StateName)
    </div>
</div>
}

This isn't working as intended and I don't understand where I am going wrong. Could anyone point out where I might be making a mistake?

2
  • There are literally hundreds of examples of this kind of thing online already, you're not the first person to have such a requirement. Couldn't you find anything which helped? Commented Jan 4, 2018 at 9:41
  • Bro I tried but not get the desired answer, there are many resources available online but as i am a beginner so i find difficult to understand them. Finally I have done it. Commented Jan 4, 2018 at 10:01

2 Answers 2

1

Try this code

@Html.DropDownListFor(model => model.CountryId , new SelectList(Model.CountryList, "Value", "Text", Model.CountryId))

also you can use viewbag,viewdata and etc

@Html.DropDownListFor(m => m.CountryId, (List<SelectListItem>)ViewBag.CountryList, "Please select")
Sign up to request clarification or add additional context in comments.

Comments

0

Inside your view file

@using(Html.BeginForm("AddState","Home",FormMethod.Post))
{ 
<div class="col-md-4">
    <div class="form-group">
        @Html.Label("Select Country")
      @Html.DropDownListFor(m=>m.CountryId,new SelectList(Model.CountryId,"value","text");
    </div>
</div>
}

Link:https://www.pluralsight.com/guides/microsoft-net/asp-net-mvc-populating-dropdown-lists-in-razor-views-using-the-mvvm-design-pattern-entity-framework-and-ajax

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.