How can I have the values from my model match the selected values in my dropdown lists? - asp.net-mvc-3

How can I have the values from my model match the selected values in my dropdown lists?
What I would like to do is to have the dropdown list reflect the property value of the model. I've only been able to show the same value in all of the dropdown lists. I've been trying to do this:
#Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s =>
new SelectListItem { Text = s.ToString(), Value = s.ToString(),
Selected = s.ToString().Equals(Model.Enrollments.FirstOrDefault().classDays) }))
but with no luck.
A snippet of my Enrollment model:
public string[] weekDays = new string[6] { "Day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
public string[] WeekDays
{
get { return weekDays; }
}
My view is of type: #model SchoolIn.Models.Student but I would like to interject another model, Model.Enrollments and minipulate the dropdown list items.
<table>
<tr>
#{
int cnt = 0;
List<SchoolIn.ViewModels.EnrolledCourseData> courses = ViewBag.Courses;
foreach (var course in courses)
{
if (cnt++ % 4 == 0)
{
#: </tr> <tr>
}
#: <td >
<br /><br /><br />
<input type="checkbox"
name="selectedCourses"
value="#course.CourseID"
#(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")))
/>
#*course.CourseID #: #course.Title*#
#course.Title<br /> <br />
if (Model.Enrollments != null)
{
#Html.DropDownList("searchString", Model.Enrollments.FirstOrDefault().WeekDays.Select(s => new SelectListItem { Text = s.ToString(), Value = s.ToString(), Selected = s.ToString().Equals(Model.Enrollments.FirstOrDefault().classDays) }))
}
#:</td>
}
#:</tr>
}
</table>

#Html.DropDownListFor( x => x.courseId, new SelectList(LookupUtils.AvailableCourcesList(), "Value", "Text", Model.courseId))
LookupUtils is a static class have:
public static List<SelectListItem> AvailableCourcesList()
{
var dataContext = new YourDataContext( );
var data = dataContext.GetCourcesFn().ToList();
var result = ( from res in data
select new SelectListItem()
{
Text = res.courseName,
Value = res.courseId.ToString()
} ).ToList();
return result;
}

Related

.NET Core 6 Pull Down Menu Selection to Group through View Model

I am having partial success searching / grouping data through a viewmodel:
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Model
using System.ComponentModel.DataAnnotations; // Date Format
namespace Project01Name.Models
{
public class Class01Name
{
public int Id { get; set; }
public string? String01Name { get; set; }
public string? String02Name { get; set; }
public int? Int01Name { get; set; }
public bool? Bool01Name { get; set; }
[DataType(DataType.Date)]
public DateTime? DateTime01Name { get; set; }
}
}
**
View Model
**
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Project01Name.Models.ViewModelsName
{
public class SearchByGroupName
{
public List<Class01Name>? Class01NameList { get; set; } // A list of movies.
public SelectList? String02NameSelection { get; set; } // A SelectList containing the list of genres. This allows the user to select a genre from the list.
public string? String02NameSelected { get; set; } // MovieGenre, which contains the selected genre.
public string? SearchString { get; set; } // SearchString, which contains the text users enter in the search text box.
}
}
Controller Action Method
// GET: String01Names
public async Task<IActionResult> Index2(string class01NameGroup, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> string02NameQuery = from m in _context.Class01Name
orderby m.String02Name
select m.String02Name;
var selectVariable = from m in _context.Class01Name
select m;
if (!string.IsNullOrEmpty(searchString))
{
selectVariable = selectVariable.Where(s => s.String01Name!.Contains(searchString));
}
if (!string.IsNullOrEmpty(class01NameGroup))
{
selectVariable = selectVariable.Where(x => x.String02Name == class01NameGroup);
}
var string02NameVM = new SearchByGroupName
{
String02NameSelection = new SelectList(await string02NameQuery.Distinct().ToListAsync()),
Class01NameList = await selectVariable.ToListAsync()
};
return View(string02NameVM);
}
View
#model Project01Name.Models.ViewModelsName.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" asp-items="Model.String02NameSelection"> <option value="">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
#*<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a> *#
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Not filtering data...simply changes pull down menu back to "All,"
displaying all data. Data not filtered.
**Question: ** What in the code has to be changed to have the data filtered successfully?
Well, seems you wanted to implement searching functionality in way, so that you can filter with the dropdown and search box and finally if you select All as dropdown value you want to load all the list without any filter and shorting means the full list which comes at first view.
If so, you need to use javascript for your dropdown change event as cshtml doesn't deal with change event. In addition, as you are using asp.net core MVC which would return HTML View altough, we need json data for Ajax reponse but we are would bee getting HTML View. So Ajax success Function will through an error where we would use filter with All parameter.
Modification Required:
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Note:
As you can see, in success function we are doing nothing, because it will always throuh an error because we are not returning json. Thus, we will work in error section. indow.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";. Here, for your understanding, we will call this function when we select All as our dropdown value in that scenario, we will pass All and nothing , nothing will convert into null and all will be our search key.
Modify Your Existing View:
In your existing view, replace blow dropdown code snippet , means the select items
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Note: If you notice I hav introduced a id id="allId" which will be using on dropdown change event.
Controller:
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Complete Demo:
Full Controller With Seed Model Class Value:
public class SearchController : Controller
{
public static List<Class01Name> listOfClass01Name = new List<Class01Name>()
{
new Class01Name() { Id =101, String01Name ="Titanic",String02Name = "Romantic", Int01Name =01, Bool01Name = false, DateTime01Name = new DateTime(2023-01-15) },
new Class01Name() { Id =102, String01Name ="Forest gump",String02Name = "Motivational", Int01Name =02, Bool01Name = true, DateTime01Name = new DateTime(2023-01-12) },
new Class01Name() { Id =103, String01Name ="Spider Man",String02Name = "Action", Int01Name =03, Bool01Name = false, DateTime01Name = new DateTime(2023-01-10) },
new Class01Name() { Id =104, String01Name ="Harry Potter",String02Name = "Suspense", Int01Name =04, Bool01Name = true, DateTime01Name = new DateTime(2023-01-13)},
};
public List<SelectListItem> String02NameSelectionList = new List<SelectListItem>()
{
new SelectListItem { Text = "Motivational", Value = "Motivational" },
new SelectListItem { Text = "Romantic", Value = "Romantic" },
new SelectListItem { Text = "Action", Value = "Action" },
new SelectListItem { Text = "Comedy", Value = "Comedy" }
};
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Full View:
#model DotNet6MVCWebApp.Controllers.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" name="searchString" />
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Output:

Sent form (list object) to controller AJAX MVC

I want sent form (list of object) with ajax. But the function serialize() in JS doesnt read in controller
JS File:
function save() {
$.ajax({
url: "/Ocena/AddOcene",
method: "POST",
dataType: "html",
data: {
id: $("#KlasaDDL option:selected").val(),
dodaj: $('#formOceny').serializeArray()
},
success: function (html) {
$('#load').html(html);
}
})
}
$(function () {
var llBtn = $('#saveForm');
llBtn.click(function () {
save();
});
});
In controller I have parametrs:
public ActionResult AddOcene(string id, List<Dodaj_ocene> dodaj)
View:
#model List<biblioteka.Dodaj_ocene>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formOceny" }))
{
#Html.DropDownListFor(x => Model[0].Przedmiot, (SelectList)ViewBag.Przedmiot, "--Dostępne przedmioty--", new { #class = "form-control" })
#*#Html.DropDownList(m => Model[0].Przedmiot, *#
<p>Wprowadź rodzaj</p>
#Html.TextBoxFor(m => Model[0].Rodzaj, new { #class = "form-control" })
<p>Wprowadź Opis</p>
#Html.TextBoxFor(m => Model[0].Opis, new { #class = "form-control" })
<p>Wybierz wagę ocen:</p>
#Html.DropDownListFor(m => Model[0].Waga, new SelectListItem[] {
new SelectListItem{ Value = "5", Text = "V", Selected = Model[0].Waga == 5 } ,
new SelectListItem{ Value = "4", Text = "IV", Selected = Model[0].Waga == 4 } ,
new SelectListItem{ Value = "3", Text = "III" , Selected =
}, new { #class = "form-control" })
<br /> <br />
<table class="table">
<tr>
</tr>
#for (var index = 0; index < Model.Count; index++)
{
<tr>
<td>#Model[index].ImieNazwisko </td>
<td>
#Html.DropDownListFor(m => Model[index].Wartosc, new SelectListItem[]{
new SelectListItem{ Value = "0", Text = "Brak oceny", Selected = Model[index].Wartosc == 0 } ,
new SelectListItem{ Value = "1", Text = "1" , Selected = Model[index].Wartosc == 1 }
} , new { #class = "form-control" })
</td>
</tr>
}
</table>
<div class="form-group">
<div></div>
<button type="button" class="btn btn-info" id="saveForm">Zapisz</button>
</div>
}
I would be very grateful for a Apparently

View with ViewModel

I have one ViewModels which contain other ViewModels
public class AllProductsViewModel
{
public ICollection<ProductSearchViewModel> ProductSearch { get; set; }
public ICollection<ProductRentViewModel> ProductRent { get; set; }
public ICollection<ProductBuyViewModel> ProductBuy { get; set; }
}
My Controller is:
public ActionResult Index()
{
var listOfProductsBuy = db.ProductsBuy.Select(x => new ProductBuyViewModel
{
Id = x.Id,
Title = x.Title,
MasterImageUrl = x.Images.FirstOrDefault().Url,
Price = x.Price,
Values = x.Value,
}).ToList();
var listOfProductsRent = db.ProductsRent.Select(y => new ProductRentViewModel
{
Id = y.Id,
Title = y.Title,
MasterImageUrl = y.ImagesRent.FirstOrDefault().Url,
Price = y.Price,
Values = y.Value,
}).ToList();
var listOfProductsSearch = db.ProductSearches.Select(z => new ProductSearchViewModel
{
Id = z.Id,
Title = z.Title,
MasterImageUrl = z.ImagesSearch.FirstOrDefault().Url,
Price = z.Price,
Values = z.Value,
}).ToList();
var viewModel = new AllProductsViewModel { ProductBuy = listOfProductsBuy, ProductRent = listOfProductsRent, ProductSearch = listOfProductsSearch };
return View(viewModel);
}
}
And my View:
#model IEnumerable<RealEstateMarket.ViewModels.AllProductsViewModel>
#{
ViewBag.Title = "Home Page";
}
<br />
<div class="row">
<div class="col-md-3">
#foreach (var item in Model)
{
<h3>#item.ProductBuy.Select(x => x.Title)</h3>
<div>
<img height="100" width="120" class="thumbnail" src="#item.ProductBuy.Select(x => x.MasterImageUrl )" />
</div>
<h3>#item.ProductBuy.Select(x => x.Price) #item.ProductBuy.Select(x => x.Values.Currency)</h3>
}
</div>
</div>
A want to take the fields of ProductBuyViewModel,ProductRentViewModel, ProductSearchViewModel
When I start this code i get the error: The model item passed into the dictionary is of type 'RealEstateMarket.ViewModels.AllProductsViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[RealEstateMarket.ViewModels.AllProductsViewModel]'.
change this
#model IEnumerable<RealEstateMarket.ViewModels.AllProductsViewModel>
to
#model RealEstateMarket.ViewModels.AllProductsViewModel
and then you can access to your list
<div class="col-md-3">
#for (int index=0;index<Model.ProductSearch.Count();index++)
{
<h3>#Model.ProductSearch[index].Title</h3>
<div>
<img height="100" width="120" class="thumbnail" src="#Model.ProductSearch[index].MasterImageUrl )" />
</div>
<h3>#Model.ProductSearch[index].Price #Model.ProductSearch[index].Values.Currency)</h3>
}
</div>

selected item in dropdownlist mvc3

Mvc3 dropdownlistFor is deriving me crazy!!!
I have two selects with the same code (different tevt and values) but one of them not works.
here is my Controller code:
[Authorize(Roles = "admins")]
public ActionResult Edit(int id = -1)
{
Advertise Advertise = db.Advertises.Find(id);
if (null == Advertise)
return View("ProductNotFound");
var selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "A", Value = "A", Selected = ("A" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "B", Value = "B", Selected = ("B" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "C", Value = "C", Selected = ("C" == Advertise.Class) });
selectListItems.Add(new SelectListItem { Text = "D", Value = "D", Selected = ("D" == Advertise.Class) });
ViewBag.Class = new SelectList(selectListItems, "Value", "Text",Advertise.Class);
var selectListItems2 = new List<SelectListItem>();
selectListItems2.Add(new SelectListItem { Text = "Image", Value = "Image", Selected = ("Image" == Advertise.FileType) });
selectListItems2.Add(new SelectListItem { Text = "Flash", Value = "Flash", Selected = ("Flash" == Advertise.FileType) });
ViewBag.Type = new SelectList(selectListItems2, "Value", "Text",Advertise.FileType);
return View(Advertise);
}
and here is my view code:
<tr>
<td class="label">
#Html.LabelFor(model => model.Class) :
</td>
<td class="editor-field">
#Html.DropDownListFor(model => model.Class, (SelectList)ViewBag.Class)
#Html.ValidationMessageFor(model => model.Class)
</td>
</tr>
<tr>
<td class="label">
#Html.LabelFor(model => model.FileType) :
</td>
<td class="editor-field">
#Html.DropDownListFor(model => model.FileType, (SelectList)ViewBag.Type)
#Html.ValidationMessageFor(model => model.FileType)
</td>
</tr>
the secound select works perfectly and the first one (class) doesn't select the selected item on page load.
and for the record, the value stored in the database is C.
please help!!!
What a ...!!!!
I found out the reason of not working select is: the name of my variable (ViewBag.Class) is the same as my Field in the model!!! I change ViewBag.Class to ViewBag.glass (just to change the name) and it worked!!!
thanks anyway.
I hope it helps somebody which has this problem!!!

Asp.net mvc razor with validate.unobtrusive

Model----------------------
public class Test
{
[Required(ErrorMessage = "Must Be Select ")]
public string TestList { get; set; }
}
Controller-----------------
public ActionResult Index(){
Test test = new Test();
string code = "11";
Dictionary<string, string> selectList = new Dictionary<string, string>();
selectList.Add("33", "33 value");
selectList.Add("22", "22 value");
selectList.Add("11", "11 value");
ViewBag.TestList = selectList.Select(x => new SelectListItem {
Text = x.Value, Value = x.Key, Selected = x.Key.Equals(code)
}).ToList();
return View(test);
}
View-----------------------
#model ~~~
#Html.DropDownListFor(model => model.TestList, null, "--SelectThis--")
i use c#, mvc3, razor with jquery.unobtrusive
that code are cool
but has problem -- html source view
<select name="TestList" id="TestList"></select>
<select name="TestList" id="TestList" data-val=true data-val-required="Must Be Select">
i want second result..
how can i do??
If you want the second result ensure that this #Html.DropDownListFor helper is inside a form:
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.Code, null, "--SelectThis--")
<input type="submit" value="OK" />
}
Also passing null as second argument is unlikely something that will work. You probably meant:
#using (Html.BeginForm())
{
#Html.DropDownListFor(
model => model.Code,
new SelectList(ViewBag.TestList, "Value", "Text"),
"--SelectThis--"
)
<input type="submit" value="OK" />
}
and what I would strongly recommend you is the following:
Model:
public class Test
{
[Required(ErrorMessage = "Must Be Select ")]
public string TestList { get; set; }
public IEnumerable<SelectListItem> TestList { get; set; }
}
Controller:
public ActionResult Index()
{
var selectList = new Dictionary<string, string>
{
{ "33", "33 value" },
{ "22", "22 value" },
{ "11", "11 value" },
};
var model = new Test
{
Code = "11",
TestList = selectList.Select(x => new SelectListItem
{
Text = x.Value, Value = x.Key
})
};
return View(model);
}
View:
#using (Html.BeginForm())
{
#Html.DropDownListFor(
model => model.Code,
new SelectList(Model.TestList, "Value", "Text"),
"--SelectThis--"
)
<input type="submit" value="OK" />
}

Resources