Selected Option is not Working in MVC Razor View - asp.net-mvc

I'm unable to get selected value in dropdown using simple below code -
<select class="form-control" id="team-name" name="gameTypes">
#{long selectedOption = #ViewBag.HomeTeamId;}
#foreach (var item in Model.teams)
{
<option value="#item.TeamId" data-logo="#item.LogoURL" selected="#(selectedOption == #item.TeamId ? "selected" : "")">#item.FullName</option>
}
</select>

I would do it like this:
Write your method to get the needed Teams in a List<SelectListItem> and then in your controller put the values in a ViewBag (ViewBag.Teams = GetTeams();)
For exmaple:
[NonAction]
private List<SelectListItem> GetTeams()
{
IEnumerable<Team> teams = new List<Team>();
//fill the teams here from the DB
return teams.Select(team => new SelectListItem
{
Text = team.TeamName, //here you can select the property that you want to show as text in the dropdown
Value = team.ID.ToString()
}).ToList();
}
And in your view, retrieve
#{
List<SelectListItem> teams = ViewBag.Teams as List<SelectListItem>;
}
And here define your dropdown and pass teams as the datasource:
<div class="col-md-6 form-group">
#Html.LabelFor(model => model.TeamId, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.TeamId, teams, "Select a team", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeamId, "", new { #class = "text-danger" })
</div>

Related

How to get values of disabled dropdownFor in mvc controller

I have a dropdownListFor controls which are cascade in nature on edit i do need to disabled the below cascaded dropdown lists until the values get changed from the first one , so below is my code of dropdown list
<div class="form-group">
#Html.LabelFor(model => model.Program_Id, "Program_Id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Program_Id", null, htmlAttributes: new { #class = "form-control", #id = "ddlPrograms" })
#Html.ValidationMessageFor(model => model.Program_Id, "", new { #class = "text-danger" })
</div>
</div>
I am making them disable using javascript
document.getElementById("ddlYear").disabled = true;
document.getElementById("ddlBlocks").disabled = true;
document.getElementById("ddlModules").disabled = true;
But on Edit when I submit the forms instead of selected value they send 0 to the controller . how to fix that issue if i am using hidden field then how i would be able to access this hidden field value as i am using entity framework and below is my controller edit post method
public async Task<ActionResult> Edit([Bind(Include = "Course_Id,Course_Name,Course_Code,Course_Visibility,Course_Start_Date,Course_End_Date,Block_Id,Module_Id,Program_Id,Year,Course_Description,Course_Image,Course_Category_Id,Course_Content_File_Path,Course_announcement,Course_Tags,Status,Course_Short_Name,Date_Created,Date_Modified")] Courses courses)
{
if (ModelState.IsValid)
{
db.Entry(courses).State = EntityState.Modified;
if (db.SaveChanges() > 0)
{
TempData["UpdatedMessage"] = "Updated Successfully";
}
// await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Block_Id = new SelectList(db.Blocks, "Id", "Name", courses.Block_Id);
ViewBag.Course_Category_Id = new SelectList(db.Courses_Category, "Id", "Category_Name", courses.Course_Category_Id);
ViewBag.Module_Id = new SelectList(db.Moduels, "Id", "Name", courses.Module_Id);
ViewBag.Program_Id = new SelectList(db.Programs, "Id", "Program_Title", courses.Program_Id);
ViewBag.Year = new SelectList(db.Years, "Id", "Name", courses.Year);
return View(courses);
}
Thanks in advance

how to insert dropdown selected value into database

i have one dropdownlist this value coming from another table so in this dropdown selected value insert into another table
see our image
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanytypeID, new { #class = "form-label semibold" })
#Html.DropDownList("CompanyType", null, "--- Select CompanyType Name ---", new { #class = "select2-arrow" })
#Html.ValidationMessageFor(model => model.CompanytypeID, "", new { #style = "color:red" })
</fieldset>
</div>
public void CompanyType_Bind()
{
DataSet ds = dDSP.Get_CompanyType();
List<SelectListItem> companylist = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
companylist.Add(new SelectListItem { Text = dr["CompanyType"].ToString(), Value = dr["CompanytypeID"].ToString() });
}
ViewBag.CompanyType = companylist;
}
public DataSet Get_CompanyType()
{
SqlCommand cmd = new SqlCommand("Select * From UserType", constr);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
Error page
Your SELECT element name should match with your property name. With your current code, you are generating a select element with name "CompanyType", But in your view model(Department) your property name is CompanyTypeId.
For model binding to work, the input element name should match with the property name. So use the same name for your SELECT element and you should be good.
#Html.DropDownListFor(x=>x.CompanyTypeId, ViewBag.CompanyType as List<SelectListItem>,
"Select CompanyType", new { #class = "select2-arrow" })
Going further, do not post link to images of your code. Instead include the relevant code in the question itself.
You haven't tied your the dropdown for your code to any property of your Department model.
#Html.DropDownList("CompanyType", null, "--- Select CompanyType Name ---", new { #class = "select2-arrow" })
will generate a select element with the name CompanyType.
From your Validator code you can see that you want to tie it to CompanytypeID
Easiest thing to do would be to change you dropdown declaration to DropDownListFor and "bind" it to CompanytypeID
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanytypeID, new { #class = "form-label semibold" })
#Html.DropDownListFor(m => m.CompanytypeID, ViewBag.CompanyType as IEnumerable<SelectListItem>, "--- Select CompanyType Name ---", new { #class = "select2-arrow" })
#Html.ValidationMessageFor(model => model.CompanytypeID, "", new { #style = "color:red" })
</fieldset>
</div>
It would be good to see your entire cshtml page.
I'd also recommend using ViewModels. It looks like you are POST'ing back your entity model which is why your putting this list in a ViewBag.

System.NullReferenceException in mvc partial view when passing a list

I am trying to add a list in search box in partial view, but I am always getting System.NullReferenceException. A similar option is working when I keep as a separate view. I am not what I am doing wrong when passing List?
Following is the snippet from views and controllers:
1] _layout.cshtml:
<div class="row">
#Html.Partial("SearchBarPartial2", Model)
</div>
2] SearchPartialView2.cshtml:
<div class="form-group">
#using (Html.BeginForm("SearchBarPartial2", "Search"))
{
#Html.LabelFor(m => m.CompanyList, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(
m => m.CompanyList,
new SelectList(Model.CompanyList, "fldt", "Value", Model.CompanyList.First().Value),
new { #class = "form-control" }
)
</div>
}
</div>
3] SearchController.cs:
public ActionResult SearchBarPartial2(cmpnytable cmpnytable1)
{
List<Company> objcompany = new List<Company>();
objcompany = GetCompanyList();
SelectList objlistofcompanytobind = new SelectList(objcompany, "ID", "Name", 0);
cmpnytable1.CompanyList = objlistofcompanytobind;
return View(cmpnytable1);
}
Your drop down list declaration already shown evidence of the error:
#Html.DropDownListFor(m => m.CompanyList, new SelectList(Model.CompanyList, "fldt", "Value", Model.CompanyList.First().Value), new { #class = "form-control" })
As Stephen said, you're assigned the model binding expression pointed to CompanyList, which becomes the source of all option tags to be rendered. It has no sense to pass the SelectList items as both binding target and source of the option list.
To resolve this issue, place additional model property with integer/string type for holding DropDownList selection result as this:
// Model
public class cmpnytable
{
// other properties here
public int SelectedId { get; set; }
}
// View
#model myproj.Models.cmpnytable
#Html.DropDownListFor(m => m.SelectedId, Model.CompanyList, new { #class = "form-control" })
Since CompanyList itself passed to view as SelectList, it's no use to create new instance of SelectList on the view.

MVC send dropdown value to databse and post it in table

Hi i am new in mvc and I'm trying to send my dropdown value to database and post it to table, any suggest best way how it will work ? .. thanks in advance
ContactController.cs
public ActionResult Create()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "English", Value = "0", Selected = true });
items.Add(new SelectListItem { Text = "German", Value = "1" });
items.Add(new SelectListItem { Text = "Spanish", Value = "2"});
items.Add(new SelectListItem { Text = "Italian", Value = "3" });
ViewBag.LanguageList = items;
return View();
}
Create.cshtml
<div class="editor-label">
#Html.LabelFor(model => model.language)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.language, new SelectList(ViewBag.LanguageList))
#Html.ValidationMessageFor(model => model.language)
</div>
Index.cshtml
<td>
#Html.DisplayFor(modelItem => item.language)
</td>
Ok, put your Dropdown selection in a form with a submit button:
using (Html.BeginForm("Create", "ContactController", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="editor-label">
#Html.LabelFor(model => model.language)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.language, new SelectList(ViewBag.LanguageList))
#Html.ValidationMessageFor(model => model.language)
</div>
<input type="submit" value="Enable" class="btn btn-link" />
}
Controller:
//This action can only be accessed with the Http.Post verb
[HttpPost]
//Validate the antiforgerytoken we set with `#Html.AntiForgeryToken()` in the view (Prevents CSRF attacks)
[ValidateAntiForgeryToken]
public ActionResult Create(YourModel model)
{
//Your model will now contain the value of the selected dropdown if you have wired up your model correctly.
//Connect to db, persist model.language
return View();
}

Using a html select box with razor

I have a html selector, and I want to use the selected value for my "model => model.type" in my form. Is there a way to set the value in my #Html.EditorFor(model => model.type) to the value of the selector?
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Bet</legend>
<div class="editor-label">
#Html.LabelFor(model => model.type)
</div>
<div class="editor-field">
<select id ="type">
<option value="Football">Football</option>
<option value="Rugby">Rugby</option>
<option value="Horse Racing">Horse Racing</option>
</select>
#Html.EditorFor(model => model.type)
#Html.ValidationMessageFor(model => model.type)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
You can try with this options:
Model:
public string Type { get; set; }
public IEnumerable<SelectListItem> TypeList
{
get
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Football", Value = "Football"},
new SelectListItem { Text = "Rugby", Value = "Rugby"},
new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"}
};
}
}
HTML (Razor):
#Html.DropDownListFor(model => model.Type, Model.TypeList)
OR
HTML (Razor):
#Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type))
#andresdescalzo's solution (last one) works with a minor change:
#Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, "Rugby"), htmlAttributes: new { #class = "form-control" })
First: Add a selected item for dropdown list (e.g. "Rugby")
Second: remove last Model.Type and add htmlAttributes
PS: SelectedList open parentheses closed after selected item of list (here is "Rugby")
The solution provided by #andresdescalzo works only when we pass the model from Controller to the view.
public class SomeController : Controller
{
public ActionResult SomeAction()
{
return View(new SomeModelWithIEnumerationsSelectListItem())
}
}
An addition to the existing answers: If you get the exception "object reference not set to an instance of an object" when implementing #andresdescalzo's solution, you either need to:
Return the model that you are working with as #diwas mentioned
Instantiate a model on the razor page so you can call the method. This is helpful if you are using a ViewModel instead of a simple EF model.
The second can be done like this:
#{ var tempModel = new YourNameSpace.Models.YourModel(); }
#Html.DropDownListFor(model => model.Type, tempModel.TypeList, Model.Type))
This is the Razor View
<div class="editor-field col-md-3">
#Html.DropDownListFor(model => model.Servers,
Model.AvailableServers,new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SqlServerName)
</div>
Dynamic DropDown from controller
List<SelectListItem> ServersAvailable = new List<SelectListItem>();
bool IdSelected = false;
ServersAvailable.Add(new SelectListItem { Text = "......Select your server name......", Value = "" });
for (int i = 0; i < dt.Rows.Count; i++)
{
ServersAvailable.Add(new SelectListItem
{
Text = dt.Rows[i].ItemArray[0].ToString(),
Value = dt.Rows[i].ItemArray[0].ToString(),
Selected = IdSelected
});
}

Resources