Drop down list select new asp net mvc
Here's an example of how to create a dropdown list with a "Select New" option in ASP.NET MVC:
Model
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller
public class MyController : Controller
{
public ActionResult Index()
{
List<MyModel> items = new List<MyModel>();
items.Add(new MyModel { Id = 1, Name = "Item 1" });
items.Add(new MyModel { Id = 2, Name = "Item 2" });
items.Add(new MyModel { Id = 3, Name = "Item 3" });
return View(items);
}
}
View (Index.cshtml)
@model List<MyModel>
@using (Html.BeginForm())
{
@Html.DropDownListFor(model => model, new SelectList(Model, "Id", "Name"), "Select New")
<input type="submit" value="Save" />
}
In the above code, we're using the DropDownListFor
helper method to create a dropdown list. We're passing in the Model
property as the first argument, which is a list of MyModel
objects. The second argument is a SelectList
object that we're creating using the SelectList
constructor. We're passing in the Model
list as the first argument, and specifying the Id
and Name
properties as the value and text fields, respectively. The third argument is the default value for the dropdown list, which is "Select New".
Result
When you run the application and navigate to the Index action, you'll see a dropdown list with the following options:
- Select New
- Item 1
- Item 2
- Item 3
If you select "Select New" and submit the form, the Id
property of the MyModel
object will be set to 0, indicating that a new item was selected.
Note that you can customize the appearance and behavior of the dropdown list by using various options available in the DropDownListFor
helper method, such as htmlAttributes
, optionLabel
, and selectedValue
.