1

In MVC4 razor application @Html.DropDownListFor providing selectlist using ViewBag but how to set default value to that drop down is not getting.

 @Html.DropDownListFor(m => m.SlpCode, new SelectList(ViewBag.SalesEmployee1, "Value", "Description"), new { @class = "form-control" })

for that I am tried

@Html.DropDownListFor(m => m.SlpCode, new SelectList(ViewBag.SalesEmployee1, "Value", "Description", (Model.SlpCode==-1)), new { @class = "form-control" }) 

but still it will not be work. what is another solution for that?

3
  • You need to set the value of SlpCode in the controller before you pass the model to the view. If it matches one of the option values (the Value property of SalesEmployee1) then that option will be selected Commented Jun 24, 2016 at 7:13
  • I am try this and this works. Thanks for suggestion. Commented Jun 24, 2016 at 7:38
  • Simply use ViewModel.SlpCode = "DefaultValue" to set DDList default value before returning view in your controller GET method, assume you have a viewmodel. Commented Jun 24, 2016 at 7:50

1 Answer 1

1

this is what i am doing for drop down list

controller code

        public ActionResult Contact()
    {
        Contact homeViewModel = new Contact();
        homeViewModel.subject = new List<Subject>();
        homeViewModel.subject.Add(new Subject { Id = 1, subject1 = "General Customer Service" });
        homeViewModel.subject.Add(new Subject { Id = 2, subject1 = "Suggestions" });
        homeViewModel.subject.Add(new Subject { Id = 3, subject1 = "Product Support" });

        homeViewModel.Selectedid = 1; //this sets the default value for your dropdown

        return View(homeViewModel);
    }

Model code :

public class Contact
 {   [Required(ErrorMessage="Please fill the following")]
    public string name { get; set; }

    [Required(ErrorMessage = "Please Enter Correct Username")]
    [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$", ErrorMessage = "Please provide valid email id")]
    public string email { get; set; }
    public List<Subject> subject { get; set; }
    [Required(ErrorMessage="Please fill the following")]
    public string message { get; set; }
    public int Selectedid { get; set; }
}

View Code :

@Html.DropDownList("Selectedid", new SelectList(Model.subject, "Id",    "subject1", Model.Selectedid), new { @class = "form-control", id = "subject", required = "required" })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.