Topic:   Selected item is not choose in dropdownlist
Jan 09, 2021 15:11 1 Replies 36 Views PADMAKEECHU

I'm learning mvc and have a problem.

I have made a Edit view, when using a @HtmlEditorFor the gender sais either Male or Female. But when using a DropDownList it's sais select Gender.

What do I miss in the code, so the value for Gender is the selected from the db?


 

                @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })                

                    @Html.DropDownList("Gender", new List                        {                            new SelectListItem{ Text = "Male", Value="Male"},                            new SelectListItem{ Text = "Female", Value="Female"}                        }, "select Gender" )                     @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })                     @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })                

           

Prev Next
Topic Replies (1)
  1. 1
    idnkx user

    PARTH

    Try below code -

    Controller/ Action Method / Model:-

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

    namespace Mvc.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Contact()
    {
    ViewBag.Message = "Your contact page.";

    List list = new List {
    new Gender { Text = "Male", Value="Male" },
    new Gender { Text = "Female", Value="Female" }
    };

    string selectedValue = "Female";

    ViewBag.Gender = new SelectList(list, "Value", "Text", selectedValue);

    return View();
    }
    }

    public class Gender
    {
    public string Text { get; set; }
    public string Value { get; set; }
    }
    }

    View:-

    @{
    ViewBag.Title = "Contact";
    }

    @ViewBag.Title.


    @ViewBag.Message



    @Html.DropDownList("Gender", null,
    htmlAttributes: new { @class = "form-control" })

Leave a Reply
Guest User

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect