Click here to Skip to main content
14,326,246 members
Rate this:
Please Sign up or sign in to vote.
See more:
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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"))
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100