i want to set multiple dropdownlist with value from db.
Here the code:
VIEW
#Html.DropDownListFor(model => model.rcf_data.lnkt_PIC, Model.Emp_list.EmployeList, new { #class = "show-tick form-control", id = "EmployeeList9", multiple = "multiple" })
CONTROLLER
In the controller, i use MergeModel
public ActionResult Edit(String rcf_id)
{
//List<RCFHistory> list_history_status =
MergeModel model = new MergeModel();
model.rcf_history = new List<RCFHistory>();
model.rcf_history = GetRCFHistory(rcf_id);
model.rcf_data = list_rcf.Where(r => r.lnkt_name == rcf_id).FirstOrDefault();
model.Emp_list = new ListEmployeeMaster();
model.Emp_list.EmployeList = new SelectList(GetAllEmployee(), "emp_id", "emp_name");
return View(model);
}
private IEnumerable<EmployeeNameModel> GetAllEmployee()
{
list_emp = new List<EmployeeNameModel>();
string apiUrl = "http://localhost:6161/Service1.svc";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(apiUrl + string.Format("/GetAllEmployee")).Result;
if (response.IsSuccessStatusCode)
{
list_emp = (new JavaScriptSerializer()).Deserialize<List<EmployeeNameModel>>(response.Content.ReadAsStringAsync().Result);
}
return list_emp;
}
I want to set value from model.rcf_data.lnkt_PIC which is List<String> into DropDownListFor in the view. But it keep showing empty field.
For single DropDownListFor, this line work for me, and it's showing value that i get from DB:
#Html.DropDownListFor(model => model.rcf_data.lnkt_2ndapprovalid, Model.Emp_list.EmployeList, Model.rcf_data.lnkt_2ndapprovalid, new { id = "EmployeeList2", #class = "show-tick form-control" })
Just changing from DropDownListFor to ListBoxFor solved my problem. No other changes happen within my code
Related
How can I make a blank default to be displayed like " " in this #Html.DropDownListFor.
I have tried the over-rides and they don't work for this.
HTML:
<td>#Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL, new { id = "ddlTerminalID", #class = "form-control align-middle" })</td>
Controller:
public ActionResult Index()
{
var model = TCBL.GetTerminalData();
return View(model);
}
//POST: TerminalCommand/Index
/*This function will insert a user selecter terminal command into the TerminalCommand table*/
public ActionResult AddTerminalCommand(AddTerminalCommandVM input)
{
TerminalCommand terminalCommand = new TerminalCommand();
terminalCommand.TerminalID = input.TerminalID;
terminalCommand.Command = input.CommandID;
terminalCommand.CommandValue = input.CommandValue;
TCBL.AddTerminalCommand(terminalCommand);
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "TerminalCommand");
return Json(new { Url = redirectUrl });
}
Data Layer:
/*Gets All termianls for the terminalsDDL and all terminal Cmds for Model.TerminalCommands*/
public TerminalCommandVM GetTerminalData()
{
TerminalCommandVM terminals = new TerminalCommandVM();
//For Terminal drop downs
terminals.TerminalsDDL = TCDA.GetTerminalsDropDown();
//For terminal cmd lists
terminals.TerminalCommands = TCDA.GetAll();
//For helpdescription
terminals.HelpDescriptions = TCDA.GetAllHelpDescriptionValues();
terminals.HelpDescriptionID = TCDA.GetAllHelpDescriptionIDs();
//For TerminalCommandLookupsDDL
List<SelectListItem> terminalCommandLookups = new List<SelectListItem>();
var terminalCommandLookupsResults = TCDA.GetAllTerminalCommandLookups().OrderBy(o => o.Name); //.Where(x => x.Name.Contains("S3"));
if (terminalCommandLookupsResults != null)
{
foreach (var item in terminalCommandLookupsResults)
{
SelectListItem newItem = new SelectListItem();
newItem.Text = item.Name;
newItem.Value = item.ID.ToString();
terminalCommandLookups.Add(newItem);
}
}
var terminalCommandValues = TCDA.GetAllTerminalCommandValues();
terminals.TerminalCommandValues = terminalCommandValues;
terminals.TerminalCommandLookupsDDL = terminalCommandLookups;
return terminals;
}
Bottom is data access layer, where the CA gets the data for display. I believe HTML should have some sort of default blank selection though..
You can add a blank default before the for loop in your Data Layer
SelectListItem newItem = new SelectListItem();
newItem.Text = "";
newItem.Value = "";
terminalCommandLookups.Add(newItem);
you can use this overload of Dropdownlistfor -
Html.DropDownListFor(Expression<Func<dynamic,TProperty>> expression, IEnumerable<SelectLestItem> selectList, string optionLabel, object htmlAttributes)
like this
<td>#Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL,"", new { id = "ddlTerminalID", #class = "form-control align-middle" })</td>
This question already has answers here:
#Html.DropDownListFor how to set default value [duplicate]
(4 answers)
Closed 5 years ago.
I Have MVC Razor view with DropdownListFor. I wanna set a default value to that DropdownListFor. I have bind dropdown for using viewbag. and in the viewbag come list and in the list store one Flag property. now i want Flag is 1 then this value I wanna set in the dropdown list. always in the list Flage = 1 is only one object come and other object flag = 0.
This is my view =>
#{ var CategoryList = ViewBag.Category as IEnumerable<ABCBAL.CategoryBAL>; }
#Html.DropDownListFor(model => model.CatId, new SelectList(CategoryList , "CatId", "Category"), new { #class = "form-control", #id = "ddlCat"})
This my controller method =>
public ActionResult EditCat(int UserId)
{
Users Userobj = new Users();
ViewBag.Category = Userobj.GetAllcategoryById(UserId).Data;
return PartialView(Cat);
}
This is my User.cs class Method =>
public Status GetAllcategoryById(int UserId)
{
Status Status = new Status();
DataSet ds = DataAccess.ExecuteDataset(Settings.ConnectionString(), "GetAllcategoryById", UserId);
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
List<CategoryBAL> CatList = new List<CategoryBAL>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CategoryBAL objCat = new CategoryBAL();
objCat.CatId = Convert.ToInt32(ds.Tables[0].Rows[i]["CatId"]);
objCat.Category = ds.Tables[0].Rows[i]["Category"].ToString();
objCat.Falge = Convert.ToInt32(ds.Tables[0].Rows[i]["Falge"]);
CatList.Add(objCat);
}
Status.Result = true;
Status.Data = CatList;
}
else
{
Status.Result = false;
}
return Status;
}
This is my code and here one flage is come 1 then i want to flage is 1 then default selected in the drop down.
You can set the value from your model like this:
#Html.DropDownListFor(model => model.CatId, new SelectList(CategoryList , "CatId", "Category"), new { #class = "form-control", #id = "ddlCat",**#value = Model.CatId**})
I am using the bootstrap selectpicker for a multiselect dropdown menu to filter items of a table in a mvc5 web app. Everything works fine so far, but i am having trouble to keep the selected filters selected after submitting. So i can read the selected filters in the controller, but after that, there is only the first previously selected filter still shown as selected after the submit. I want all chosen filters to be still selected. How can I reach this?
Here ist my Code, the ViewModel contains:
public MultiSelectList AvailableUser_ID { get; set; }
private List<string> _selectedUserId = new List<string>();
public List<string> SelectedUserId
{
get { return _selectedUserId; }
set { _selectedUserId = value; }
}
The Controller (Post):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "SelectedUserId,SelectedUserInteractionTypesId")] IndexUserInteractionViewModel indexUserInteractionViewModel)
{
indexUserInteractionViewModel.UserInteractionViewModels = new List<UserInteractionViewModels>();
indexUserInteractionViewModel.AvailableUser_ID = new MultiSelectList(db.AspNetUsers.ToList(), "Id", "Email", indexUserInteractionViewModel.SelectedUserId);
// Filter Function: selectedUserId contains all the Ids of the previously selected filters
foreach (string selectedUserId in indexUserInteractionViewModel.SelectedUserId)
{
if (userInteraction.AspNetUsers_Id.Equals(selectedUserId))
// ...
}
}
And the View:
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker();
});
</script>
<th>#Html.DropDownListFor(Model => Model.SelectedUserId, Model.AvailableUser_ID as MultiSelectList, new { #id = "userFilter", #class = "selectpicker", #multiple = "mulitple", data_live_search = "true" })</th>
So how can I keep the Selection selected?
Unfortunately I have little js-knowledge and i am assuming that i could solve it in the js-script. I am hoping for some experts here. Thank you!
A colleague of mine found a solution, this is what works:
var selectedList = #Html.Raw(Json.Encode(Model.SelectedUserId));
if(selectedList.length > 0){
var result = '[';
for (i = 0; i < selectedList.length; i++) {
result += '"' + selectedList[i] + '",';
}
result = result.slice(0, -1); //remove last comma
result += ']';
$('.selectpicker').selectpicker('val', JSON.parse(result1));
}else{
$('.selectpicker').selectpicker();
}
I crated SelectList selectList with data from my Entities.
And now I want send value from DropDownList to Entitie.
everything is OK (I got value from selected item) , but I got his error et the end
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'Przelew.DaneKont'.
#Html.DropDownList("Przelew.DaneKont", ViewBag.DaneKontList as SelectList, "-- Wybierz kontot --")
Viewmodel:
#Html.DropDownList("Przelew.DaneKont", ViewBag.DaneKontList as SelectList, "-- Wybierz kontot --")
Controller:
[Authorize]
[HttpGet]
public ActionResult WykonajPrzelew( ) {
using (var context = new BankAppEntities1())
{
konto = context.Konto.SqlQuery("SELECT * FROM dbo.Konto WHERE UserId = '" + userIdValue + "' ").ToList();
}
WykonajPrzelewMultipleView mymodel = new WykonajPrzelewMultipleView();
mymodel.Konta = konto;
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in konto){
items.Add(new SelectListItem { Text = item.Nazwa+ " Saldo :"+item.Saldo , Value = item.KontoId+"" });
}
ViewBag.DaneKont = items;
SelectList selectList = new SelectList(items, "Value", "Text");
ViewBag.DaneKontList = selectList;
return View(mymodel);
}
[Authorize]
[HttpPost]
public ActionResult WykonajPrzelew(WykonajPrzelewMultipleView model)
{
string imie = model.Przelew.ImieOdbiorcy;
string nazwisko = model.Przelew.NazwiskoOdbiorcy;
int numerOdbiorcy = Convert.ToInt32(model.Przelew.NumerRachunkuOdbiorcy);
int kontoID = Convert.ToInt32(model.Przelew.DaneKont); // I got Value from List
string tytul = model.Przelew.Tytuł;
string ulica = model.Przelew.Ulica;
string numerdomu = model.Przelew.nrdomu;
string kod = model.Przelew.Kodpocztowy;
string miasto = model.Przelew.Miasto;
string tyt =model.Przelew.Tytuł;
decimal kwota = model.Przelew.Kwota;
DateTime date = System.DateTime.Now;
using (var context2 = new BankAppEntities1())
{
var dane = new Przelew { Imie = imie, Nazwisko = nazwisko, NumerKontaOdbiorcy = numerOdbiorcy, KontoId = "1", NumerKontaNadawcy = 3444666, Ulica = ulica, Nr_domu = numerdomu,Kod_pocztowy="343", Miasto = miasto, Typ = "Normlany", UserId = userIdValue,Kwota=kwota , Date=date , Tytul=tyt };
context2.Przelew.Add(dane);
context2.SaveChanges();
}
return View();
}
You need another property on your model such as DaneKont, and change your view to the following:
#Html.DropDownList("DaneKont", (SelectList)ViewBag.DaneKontList, "-- Wybierz kontot --")
On postback, DaneKont will hold the selected value.
I have a subject dropdownlist for a contact form. I always want the Other to be at the bottom of the list. The reason I ask this is because I created a controller so if I wanted to add more subjects I could do so. Anyways suggestions or ways I could go about making sure that the position of the Other subject is always on the bottom of the list?
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
subjects.Insert(0, new Subject() { ID = 0, Name = "- Please Select -" });
ViewData["Subjects"] = subjects;
}
I have posted my combo box if this is of any help
You should simply use the proper overload of the DropDownList helper when rendering your dropdown in the view instead of trying to insert some dummy items into the collection:
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
ViewData["Subjects"] = subjects;
}
and then in the view:
#Html.DropDownList(
"selectedSubject",
new SelectList(ViewData["Subjects"] as List<Subject>, "ID", "Name"),
"- Please Select -"
)
Now this being said, everytime I see someone using ViewData/ViewBag/ViewCrap instead of strongly typed views and view models I get sick and I feel myself into the obligation to show the correct way of doing this.
As always you start with a view model:
public class MyViewModel
{
public string SelectedSubject { get; set; }
public IEnumerable<SelectListItem> Subjects { get; set; }
}
then you have a controller action which will take care of populating this view model:
public ActionResult Index()
{
// TODO: You definitively don't want to hardcode your repository like this
// but use a constructor injection or this action will be impossible to unit test
IRepository<Subject> subjectRepository = new Repository<Subject>();
var subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
var model = new MyViewModel
{
Subjects = subjects.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
})
};
return View(model);
}
and finally in your strongly typed view:
#model MyViewModel
#Html.DropDownListFor(
x => x.SelectedSubject,
new SelectList(Model.Subjects, "Value", "Text"),
"- Please Select -"
)
DropDownList1.DataSource = YourDataSource;
DropDownList1.DataBind();
//Insert Other subject to the end
ListItem litem = new ListItem(" Other subject ", "value");
DropDownList1.Items.Insert(DropDownList1.Items.Count, litem);
Modify your code as shown below:
public void PrepareSubjectCombo()
{
// Grab a list of subjects for the dialog box
IRepository<Subject> subjectRepository = new Repository<Subject>();
List<Subject> subjects = subjectRepository.GetAll().OrderBy(t => t.Position).ToList();
subjects.Insert(0, new Subject() { ID = 0, Name = "- Please Select -" });
// Add this line
// Make sure you use the correct ID for the "Other" subject
subjects.Add(new Subject() { ID = 100, Name = "Other" });
// If you determine the ID based on the list, simply set the ID = subjects.Count + 1
int otherID = subjects.Count + 1;
subjects.Add(new Subject() { ID = otherID, Name = "Other" });
ViewData["Subjects"] = subjects;
}