Display Default value into dropdown list in mvc4 - c#

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?

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" })

Related

Fill Dropdownlist countries based on User login in ASP.NET MVC

I want to fill dropdownlist countries based on User login into my application. If user is not logged on then the default country will be displayed. Please help me and guide me how to fill dropdown based on user logon country. Any help is highly appreciated.
AspUsers table -- When user register, all the information goes to this table
My LeadingClass data Model
public int? Type { get; set; }
public string Country { get; set; }
My LeadingFilterVM View Model
public int? Type { get; set; }
public IEnumerable<SelectListItem> TypeList { get; set; }
public string Country { get; set; }
public IEnumerable<SelectListItem> CountriesList { get; set; }
public IPagedList<LeadingClass> Leadings { get; set; }
My LeadingDatabaseHandle
public List<LeadingClass> LeadingBasedonFilter(int? Type, string Country = "")
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<LeadingClass> leadingClass = new List<LeadingClass>();
string sSQL;
SqlParameter[] prms = new SqlParameter[3];
sSQL = "exec GetLeeading #Type,#country";
prms[0] = new SqlParameter("#Type", SqlDbType.Int);
prms[0].Value = Sire;
prms[1] = new SqlParameter("#Country", SqlDbType.VarChar);
prms[1].Value = Country;
ds = clsUtilities.CreateCommandwithParams(sSQL, prms);
DataTable dataTable = ds.Tables[0];
foreach (DataRow dr in dataTable.Rows)
{
leadingClass.Add(
new LeadingClass
{
Id = Convert.ToInt32(dr["Id"]),
Name= Convert.ToString(dr["Name"]),
}
);
}
return leadingClass;
}
My Home Controller
[HttpGet]
public ActionResult Leading(int? type, string country,int? pageNumber)
{
LeadingDatabaseHandle leadingDatabaseHandle = new LeadingDatabaseHandle();
IEnumerable<LeadingClass> data;
if (type!=null)
{
data = leadingDatabaseHandle.LeadingBasedonFilter(type.Value, country);
}
else
{
data = leadingDatabaseHandle.LeadingSiresAll();
}
LeadingFilterVM model = new LeadingFilterVM
{
Type = type,
Country = country,
TypeList = new List<SelectListItem>
{
new SelectListItem{ Text = "General", Value = "1" },
new SelectListItem{ Text = "Advance", Value = "2" },
},
CountriesList = new List<SelectListItem>
{
new SelectListItem {Value = "NZ", Text="New Zealand" },
new SelectListItem {Value = "AUS", Text = "Australia" },
new SelectListItem {Value = "FR", Text = "France" },
new SelectListItem {Value = "GB", Text = "Great Britain" },
},
Leadings = data.ToPagedList(pageNumber ?? 1, 10)
};
return View(model);
}
My Leading View
#using (Html.BeginForm("Leading", "Home", FormMethod.Get))
{
<div class="col-sm-2">
#Html.DisplayNameFor(m => m.Leadings.FirstOrDefault().Type)
#Html.DropDownListFor(m => m.Type, Model.TypeList, new { #class = "form-control" })
</div>
<div class=" col-sm-2">
#Html.DisplayNameFor(m => m.Country)
#Html.DropDownListFor(m => m.Country, Model.CountriesList, new { #class = "form-control"})
</div>
<button type="submit" class="btn btn-info">Search</button>
}

How to remove items in a drop down based on an ID

I have a drop down box in my view which I would like to alter depending on the ClientID. I don't have a clue where to start with this, I thought about using Javascript but I would rather avoid it as some users could have Javascript turned off.
ViewModel:
public class ReportType {
public int ReportID { get; set; }
public string ReportName { get; set; }
}
public IEnumerable<ReportType> ReportTypeOptions = new List<ReportType>
{
new ReportType {ReportID = 0, ReportName = "Claims by Supplier"},
new ReportType {ReportID = 1, ReportName = "Department Breakdown"},
new ReportType {ReportID = 2, ReportName = "Reason Code Breakdown"},
new ReportType {ReportID = 3, ReportName = "Monthly Debiting Report"},
};
View:
#Html.DropDownListFor(m => m.ReportTypeOptions.First().ReportID, new SelectList(Model.ReportTypeOptions, "ReportID", "ReportName"), "Select Report", new { #class = "GRDropDown", #id = "ReportDD", onchange = "disableFunction()" })

How to use DropDownListFor when model is List

My model is a generic List. I want to use DropDownList for foreign key property binding.
My code is
Model
public class PersonViewModel
{
public int Id { get; set; }
public string LastName{get;set;}
public int NationalityId { get; set; }
}
public class Nationality
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller
public ActionResult Index()
{
var nationalities = new List<Nationality>
{
new Nationality{Id = 0, Name = "CHOOSE NATIONALITY..."},
new Nationality{Id = 1, Name = "POLAND"},
new Nationality{Id = 2, Name = "USA"},
new Nationality{Id = 3, Name = "CANADA"}
};
var Nationalities = new SelectList(nationalities, "Id", "Name");
var persons = new List<PersonViewModel>
{
new PersonViewModel{Id = 1, LastName = "KOWALSKI", NationalityId = 1},
new PersonViewModel{Id = 1, LastName = "SMITH", NationalityId = 2},
new PersonViewModel{Id = 1, LastName = "SCHERBATSKY", NationalityId = 3}
};
ViewBag.Nationalities = Nationalities;
return View(persons);
}
View
#model List<PersonViewModel>
#Html.EditorFor(m=> Model[0].LastName)
#Html.DropDownListFor(m => Model[0].NationalityId, (SelectList)ViewBag.Nationalities)
#Html.EditorFor(m => Model[1].LastName)
#Html.DropDownListFor(m => Model[1].NationalityId, (SelectList)ViewBag.Nationalities)
#Html.EditorFor(m => Model[2].LastName)
#Html.DropDownListFor(m => Model[2].NationalityId, (SelectList)ViewBag.Nationalities)
Anyone can tell me why NationalityId property is not bound well
I can't upload image but it's not binding at all. Every DropDownList has 'CHOOSE NATIONALITY...' .
I would recommend you using Editor templates:
First - create view Shared\EditorTemplates\PersonViewModel.cshtml containing:
#model PersonViewModel
#Html.EditorFor(m => Model.LastName)
#Html.DropDownListFor(m => Model.NationalityId, (SelectList)ViewBag.Nationalities)
And in your current view
#for (int i = 0; i < Model.Count; i++)
{
#Html.EditorFor(x => Model[i])
}
Change your view model to this
public class PersonViewModel
{
public int Id { get; set; }
public string LastName{get;set;}
public int NationalityId { get; set; }
public IEnumerable<Nationality> Nationalities {get;set;}
}
In your controller
public ActionResult Index()
{
var nationalities = new List<Nationality>
{
new Nationality{Id = 0, Name = "CHOOSE NATIONALITY..."},
new Nationality{Id = 1, Name = "POLAND"},
new Nationality{Id = 2, Name = "USA"},
new Nationality{Id = 3, Name = "CANADA"}
};
var nationalities = new SelectList(nationalities, "Id", "Name");
var persons = new List<PersonViewModel>
{
new PersonViewModel{Id = 1, LastName = "KOWALSKI", NationalityId = 1 , Nationalities = nationalities},
new PersonViewModel{Id = 1, LastName = "SMITH", NationalityId = 2, Nationalities = nationalities},
new PersonViewModel{Id = 1, LastName = "SCHERBATSKY", NationalityId = 3, Nationalities = nationalities}
};
return View(persons);
}
And in your view
#model List<PersonViewModel>
#Html.EditorFor(m => m[0].LastName)
#Html.DropDownListFor(m => m[0].NationalityId, Model[0].Nationalities)
#Html.EditorFor(m => m[1].LastName)
#Html.DropDownListFor(m => m[1].NationalityId, Model[1].Nationalities)
#Html.EditorFor(m => m[2].LastName)
#Html.DropDownListFor(m => m[2].NationalityId, Model[2].Nationalities)
Two things:
Each dropdown needs its own select list. Currently you are using the same select list for each dropdown.
You need to specify a selected value for each select list, like so:
new SelectList(nationalities, "Id", "Name", persons[0].NationalityId);

Selected value is not showing for dropdownlist in MVC 4

Model
public class LeadsVM
{
public LeadsVM()
{
this.leadsList = new List<SingleLeadVM>();
}
public IList<SingleLeadVM> leadsList { get; set; }
// For backup user and assign user
public IEnumerable<UserProfile> users { get; set; }
public LeadDetailsVM leadDetailsVM { get; set; }
[Display(Name = "Lead status")]
public IEnumerable<LeadStatus> leadStatusList { get; set; }
}
View
#for (int i = 0; i < Model.leadsList.Count; i++)
{
#Html.DropDownListFor(model => Model.leadsList[i].assignedToUserId, new SelectList(Model.users, "UserId", "Email"), "Select user", new { data_val = false, data_users = Model.leadsList[i].leadId, #class = "usersList" })
}
The reason why I am using for loop rather than foreach is that I can submit collection of data back to controller. The problem is that even if the value can be passed from View to controller and vice versa I am unable to display correct value in dropdown list(I can always see optional label).
Solution
#Html.DropDownListFor(model => Model.leadsList[i].assignedToUserId, new SelectList(Model.users, "UserId", "Email", Model.leadsList[i].assignedToUserId), "Select user", new { data_val = false, data_users = Model.leadsList[i].leadId, #class = "usersList" })
Fixed it. Turned out that I could use the 4th parameter of the SelectList constructor.
#Html.DropDownListFor(model => Model.leadsList[i].assignedToUserId,
new SelectList(Model.users, "UserId", "Email", Model.leadsList[i].assignedToUserId),
"Select user",
new { data_val = false, data_users = Model.leadsList[i].leadId, #class = "usersList" })

Bind Dropdown using mvc4

I need help to bind drop-down values from models.
Model.cs
public class BloodGroup
{
public BloodGroup()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name="Blood Group")]
public int Group { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
public class ActionType
{
public int GroupId { get; set; }
public string BloodGroup { get; set; }
}
In the Controller:
List<ActionType> actionType = GetCourses();
bGroup.ActionsList = from action in actionType
select new SelectListItem
{
Text = action.BloodGroup,
Value = ((int)action.GroupId).ToString(),
Selected = action.BloodGroup.Equals("A+")?true:false
};
return view;
public List<ActionType> GetCourses()
{
return new List<ActionType> {
new ActionType () { GroupId = 1, BloodGroup = "A+"},
new ActionType () { GroupId = 2, BloodGroup = "B+"},
new ActionType () { GroupId = 3, BloodGroup = "O+" },
new ActionType () { GroupId = 4, BloodGroup = "AB+" },
new ActionType () { GroupId = 5, BloodGroup = "A-"},
new ActionType () { GroupId = 6, BloodGroup = "B-"},
new ActionType () { GroupId = 7, BloodGroup = "O-" },
new ActionType () { GroupId = 8, BloodGroup = "AB-" }
};
}
It successfully return to view. But in view when bind dropdown it throws an error.
in view
#model MyMVC.Models.BloodGroup
#Html.DropDownListFor(m => m.Group, new SelectList(Model.ActionsList, "Value", "Text",true), "-- Select --")</li>
It returns error.
Object reference not set to an instance of an object.
Model.ActionsList is set a Null.
I don't know why it shows null, though I inherit the model.
I need help on how to bind the SelectList value to dropdown
You need to pass a instance of BloodGroup class to the view in your action method, like below:
public ActionResult YourAction()
{
List<ActionType> actionType = GetCourses();
var model = new BloodGroup()
{
ActionsList = (from action in actionType
select new SelectListItem
{
Text = action.BloodGroup,
Value = ((int) action.GroupId).ToString(),
Selected = action.BloodGroup.Equals("A+")
})
};
return View(model);
}
Then in your view:
#model BloodGroup
#Html.DropDownListFor(m => m.Group, Model.ActionsList,"-- Select --")
Notice
Using above example it'll show you the view without errors, but the selected item in your downdownList will NOT show correctly. For showing the selected item correctly, you need to change the type of Grop property to String, like below:
public class BloodGroup
{
//
[Display(Name = "Blood Group")]
public string Group { get; set; }
//
}
Then use above same action method, make your view like:
#model BloodGroup
#Html.DropDownList("Group", Model.ActionsList, "-- Select --")

Categories