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.
Related
i used value the model for drop down list,
> public class Items
> {
> public int itemcategoryid { get; set; }
> public string itemcategory { get; set; }
> public int Itemsubcategoryid { get; set; }
> public string Itemsubcategoryname { get; set; }
> }
and below the code for controller
> ItemViewModel catVM = new ItemViewModel();
> List<Items> catlist = catVM.GetCategoryInfo();
> ViewBag.categorylist = catlist;
After binding drop down list using below the HTML code, the drop down list has populated and select default name as itemcategory but did not pass id of itemcategory pass only itemcategory name for POST.
#Html.DropDownListFor(model => model.itemcategory, new SelectList(ViewBag.categorylist, "itemcategory", "itemcategory", Model.itemcategory))
if i using below the HTML Code their pass value but did not select default name
#Html.DropDownListFor(model => model.itemcategory, new SelectList(ViewBag.categorylist, "itemcategoryid", "itemcategory", Model.itemcategory))
using below the code for retrieve data
using (OracleCommand cmd = new OracleCommand("PS_Category", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Items listitems = new Items(); ;
listitems.itemcategoryid = Convert.ToInt32(reader["CATID"]);
listitems.itemcategory = reader["CATNAME"].ToString();
items.Add(listitems);
}
}
Actually i want to to select default name and pass their id how can possible it??
For Multiple dropdown Value You Use It.For Insert Value
ViewBag.DocumentId = new SelectList(_documentCategoryService.GetAll().OrderBy(a => a.Name), "Id", "Name");
For Edit You Can Use this.
ViewBag.DocumentId = new MultiSelectList(_documentCategoryService.GetAll(), "Id", "Name", _documentCategoryService.GetAllByExportId((int)id).Select(a => a.DocumentCategoryId).ToArray());
View Part:
<div class="row-fluid">
<div class="span12">
<div class="control-group">
<label class="control-label">Documents Require</label>
<div class="controls controls-row">
#Html.DropDownList("DocumentId", null, htmlAttributes: new { #placeholder = "Select Documents", #class = "span6 chzn-select documentCategories", #tabindex = "8", #multiple = "multiple", #name = "DocumentId" })
</div>
</div>
</div>
</div>
For Single DropdownValue.
ViewBag.BranchId = new SelectList(_branchService.GetAllByOrganizationId((User as CustomPrincipal).DefaultOrganizationId), "Id", "Name");
ViewBag.BranchId = new SelectList(_branchService.GetAllByOrganizationId((User as CustomPrincipal).DefaultOrganizationId), "Id", "Name", exportLetter.LcTransctionDetails.Transactions.BranchId);
<div class="span4">
<div class="control-group">
<label class="control-label">Branch</label>
<div class="controls controls-row">
#Html.DropDownList("BranchId", null, htmlAttributes: new { #class = "form-control", #id = "Branches" })
</div>
</div>
</div>
This was answered here before but some are reporting that it doesn't work for them;
#Html.DropDownListFor how to set default value
If that doesn't work, the selectlist class documentation is here
https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.selectlist.-ctor?view=aspnet-mvc-5.2#System_Web_Mvc_SelectList__ctor_System_Collections_IEnumerable_System_String_System_String_System_String_System_Object_
It is mentioned there that the constructor you used uses the last parameter as the selected value, hence you should do; (pass model.itemcategoryid in the end)
#Html.DropDownListFor(model => model.itemcategory, new SelectList(ViewBag.categorylist, "itemcategoryid", "itemcategory", Model.itemcategoryid))
If the above answer doesn't work for you, here's another way but using jquery;
Add a class htmlattribute selectLoop;
#Html.DropDownListFor(model => model.itemcategoryId, new SelectList(ViewBag.categorylist, "itemcategoryid", "itemcategory"), new { #class="selectLoop" })
Add this script to your view;
#section scripts{
<script>
// when the document is ready (server is done loading)
$(document).ready(function(){
// loop through all those with selectLoop class
$(".selectLoop").each(function(){
// get the selected value and store to variable
var selected = "#Model.itemCategoryId";
// loop through all the option inside the select
$(this).find("option").each(function(){
// check if the value attribute matches the selected variable
if($(this).attr("value") == selected){
// if match, assign the option's selected attribute to true
$(this).attr("selected",true);
}
});
});
});
</script>
}
Then in your shared/layout.cshtml, add #RenderSection("scripts", required: false) after jquery and bootstrap. See below;
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
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>
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.
I am filling out a form, however when selecting an option from the drop down list and click submit, no matter what option I select, it always parses the top one through. The displayed value never changes, so it you leave it as the default option 'please select...' and click submit, this stays as 'please select...' but the entry in the database is always the one that appears at the top of the drop down.
Here is the model:
public enum Medium
{
[Description("Teleconference & Report")]
Teleconference_Report,
[Description("Email & Telephone")]
Email_Telephone
}
[Required]
[Display(Name = "Medium")]
public Medium Medium { get; set; }
Here is the field in the form:
<div class="form-group">
#Html.LabelFor(model => model.Medium, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-5">
#Html.DropDownList("MediumID", null, "Please select...", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Medium, "", new { #class = "text-danger" })
</div>
</div>
The "MediumID" DropDownList is populated using a viewbag which is set to whatever the following returns:
// Puts all of the mediums of communication into a user friendly dropdownlist.
public List<SelectListItem> GetMediumList()
{
List<SelectListItem> mediumList = new List<SelectListItem>();
foreach (Medium state in EnumToList<Medium>())
{
mediumList.Add(new SelectListItem
{
Text = GetEnumDescription(state),
Value = state.ToString(),
});
}
return mediumList;
}
Below shows the form section for another enum called 'Frequency', but these are not changed to user friendly strings (and is working fine).
<div class="form-group">
#Html.LabelFor(model => model.Frequency, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-5">
#Html.EnumDropDownListFor(model => model.Frequency, "Please select...", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Frequency, "", new { #class = "text-danger" })
</div>
</div>
Below here, shows the two methods which turn the enums into user friendly strings:
// Returns a 'user friendly', readable version of the enum.
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
// Puts all of the same enums into a list.
public static IEnumerable<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this.
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
Finally, here is the method signature where the fields are binded/bound:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Point,ApplicationID,MediumID,Frequency,StartDate,EndDate")] TouchPoint touchPoint)
Within this method, the dropdown is passed to the view using the following:
ViewBag.MediumID = GetMediumList();
Any help is greatly appreciated.
Your model has a property named Medium but your view does not bind to that property. The name of the <select> your generating is MediumID which does not exist in your model, so the default value for Medium when you submit will Teleconference_Report (the first enum value).
Change the view to
#Html.DropDownListFor(m => m.Medium, (IEnumerable<SelectListItem>)ViewBag.MediumID, "Please select...", new { #class = "form-control" })
although I would recommend changing the ViewBag property name to say MediumList to make it more obvious that its a collection. And even better, use a view model with a property public IEnumerable<SelectListItem> MediumList { get; set; } so that the viewcan be #Html.DropDownListFor(m => m.Medium, Model.MediumList, .... ).
You also need to change the [Bind] attribute to include "Medium" (and remove "MediumID") although using a view model means the [Bind] attribute is not required.
Side note: You do not need the [Required] attribute unless you want to add a specific error message using the ErrorMessage = "..." property (an enum is always required by default unless you make the property nullable).
I have multiple dropdown list for same select list in look and want to set dropdown item selected as per loop.
How can I set specific one item of dropdown list selected in mvc dropdownlist.
Please help.
The Html.DropDownList method takes multiple parameters, one of them being a List<SelectListItem>. The individual instance of the SelectListItem is where you set the Selected property:
var item = new SelectListItem() {
Selected = /* condition */,
Value = "Some Value",
Text = "Some Text"
};
Alternatively:
Create a SelectList collection that exposes the SelectedValue property:
Model.YourSelectList = new SelectList(items /* List<SelectListItem> */,
"Value",
"Text",
37 /* selected value */);
When building the SelectList, you can set the selected item on construction using http://msdn.microsoft.com/en-us/library/dd460123.aspx
Or you can set it on an individual SelectListItem via it's Selected property ( http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.selected.aspx ) and use the single-parameter constructor of the select list, or pass it straight to the DropDownList method.
Use the HTML helper ListBoxFor.
#Html.ListBoxFor(m => m.MyPropertyId, Model.MySelectList)
To build the list of items, you can use the MultiSelectList. For example, in your controller:
public ActionResult Index()
{
// Get a collection of all product id's that should be selected.
int[] productIds = _service.GetSomeProductIds();
// Make a new select list with multiple selected items.
ViewBag.List = new MultiSelectList(
_service.Products,
"Id", // Name of the value field
"Name", // Name of the display text field
productIds ); // list of selected product ids
return View();
}
Then in your view:
#Html.ListBoxFor(m => m.ProductIds, (IEnumerable<SelectListItem>)ViewBag.List)
MVC method to bind custom list to dropdownlist and select item dynamically
if you need more details ,comment below
Create Section
#{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
}
<div class="form-group">
#Html.LabelFor(model => model.SaleOrPurchase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SaleOrPurchase, list, "-- Select Status --", new {#class= "form-control" })
#Html.ValidationMessageFor(model => model.SaleOrPurchase, "", new { #class = "text-danger" })
</div>
</div>
EDIT Section
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "SALE", Value = "SAL" });
list.Add(new SelectListItem { Text = "PURCHASE", Value = "PUR" });
IEnumerable<SelectListItem> myCollection = list.AsEnumerable();
ViewBag.SaleOrPurchase = new SelectList(myCollection, "Value", "Text", transactionTbl.SaleOrPurchase.ToString().Trim());