Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
Model

Student.cs

[Key]
public int Id { get; set; }

public string Name { get; set; }
public int CourseId { get; set; }  
public Course course { get; set; }
Course.cs

public class Course
{ 
    [Key]
    public int CourseId { get; set; }

    public string CourseName { get; set; }
}
StudentController.cs

        public ActionResult Create()
        {
            List<SelectListItem> CourseId = new List<SelectListItem>();
            CourseId.Add(new SelectListItem { Text = "1", Value = "1" });
            CourseId.Add(new SelectListItem { Text = "2", Value = "2" });
            CourseId.Add(new SelectListItem { Text = "3", Value = "3" });
            ViewBag.CourseId = CourseId;
            return View();
        }

        [HttpPost]
        public ActionResult Create(Student stud)
        {
            ViewBag.CourseId = stud.CourseId;
            return View();
        }


create.cshtml

<div class="form-group">
                @Html.LabelFor(model => model.CourseId, "CourseId", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model=>model.CourseId,new SelectList(ViewBag.CourseId))
                    @Html.ValidationMessageFor(model => model.CourseId, "", new { @class = "text-danger" })
                </div>
            </div>



Reference:
https://i.stack.imgur.com/ZKzOl.png[^]

What I have tried:

when I run this code then dropdownlist has system.web.mvc.selected item?? how to solve this issue of dropdown list?
Posted
Updated 6-Oct-19 23:24pm

1 solution

When you create the SelectList you need to tell it what properties of the objects you are binding to it are to be used for the text and the value

@Html.DropDownListFor(model => model.CourseId, new SelectList(ViewBag.CourseId, "Text", "Value"))
 
Share this answer
 
Comments
Member 14613437 7-Oct-19 7:25am    
@F-ES Sitecore thanks DropDownList Have 1 2 3 but the issue is when I create a record then give an error: Additional information: The best overloaded method match for 'System.Web.Mvc.SelectList.SelectList(System.Collections.IEnumerable, object, System.Collections.IEnumerable)' has some invalid arguments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900