I am learning MVC 4 razor,i am trying to get display member and value from drop down list but i am not able to get it, this is my code
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).change(function ()
{
var selectedItem = $("#Employee :selected").text();
var selectedValue = $("#Employee").val();
alert(selectedItem+" "+selectedValue);
//document.getElementById("#lblEmployee").innerText = selectedItem;
});
</script>
#Html.DropDownList("Employee", ViewData["lstEmp"] as SelectList)
please help me out,If any other way rather using JQuery please tell.
Controller:
public ActionResult Create()
{
var VM = new ProjectViewModel();
int projectId = 0;
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Value = "1", Text = "a" });
list.Add(new SelectListItem { Value = "2", Text = "b" });
list.Add(new SelectListItem { Value = "3", Text = "c" });
VM.ddlClientLists = list
return View("Create",VM);
}
view model:
public class VM
{
public List<SelectListItem> ddlClientLists { set; get; }
public VM(){
ddlClientLists = new List<SelectListItem>();
}
}
in create view:
#model project.Models.VM
#Html.DropDownList("ddlclientLists", Model.ddlClientLists, "select")
Related
In my edit page using EditorFor to edit the value of location.
#Html.EditorFor(model => model.location, new { htmlAttributes = new { #class = "form-control" , id = "testing" } })
But I would like to make that value edit come from a hard code list like below.
How can I make it that it defaults to the correct value and be able to select the other options.
var selectLocation = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "State", Value = "State"},
new SelectListItem {Text = "International", Value = "International"},
new SelectListItem {Text = "test2", Value = "test2"},
}, "Value", "Text");
The #Html.EditorFor() helper used to generate <input> elements, not a <select> element. You should use a property with type IEnumerable<SelectListItem> on the viewmodel:
public class ViewModel
{
public string location { get; set; }
public List<SelectListItem> Locations { get; set; }
}
And assign it inside controller action method like this:
var model = new ViewModel();
var selectLocation = new List<SelectListItem>()
{
new SelectListItem {Text = "State", Value = "State"},
new SelectListItem {Text = "International", Value = "International"},
new SelectListItem {Text = "test2", Value = "test2"},
};
model.Locations = selectLocation;
// return the view with existing viewmodel
return View(model);
Then, use #Html.DropDownListFor() helper to generate <select> element with options list:
#Html.DropDownListFor(model => model.location, Model.Locations, ...)
Note:
1) If you're already created List<SelectListItem> object, no need to convert it into SelectList object, because SelectList also has IEnumerable<SelectListItem> type for the option list.
2) Alternatively you can use ViewBag to pass the List<SelectListItem> object, but the approach above is mostly used for strongly-typed option list.
This question already has answers here:
MVC5 - How to set "selectedValue" in DropDownListFor Html helper
(5 answers)
Closed 4 years ago.
I have a stored procedure that retrieves existing data from the database and I want to set my DropDownListFor to a value that is equal to the data from the stored procedure's result. This is for an edit module.
Here is my code for my controller:
[HttpPost]
public ActionResult EditGetProjDetails(int id)
{
var vm = new ProjectsViewModel();
sp_GetProjectDetails_Result result = db_RIRO.sp_GetProjectDetails(id).FirstOrDefault();
vm.BusinessLineList = db_RIRO.sp_GetAllBusinessLine()
.Select(a => new SelectListItem
{
Value = a.BusinessLineID.ToString(),
Text = a.BusinessLine,
Selected = // what code do i put here?
})
.ToList();
vm.ProjectID = result.ProjectID;
vm.BusinessUnit = result.BusinessUnit;
return PartialView("~/Views/Project/_EditProjDetails.cshtml", vm);
This is my View:
#Html.DropDownListFor(a => a.BusinessLineID, Model.BusinessLineList, new { #class = "form-control input-sm", placeholder = "Business Line", required = "required", autocomplete = "off" })
and here is my ViewModel:
public int BusinessLineID { get; set; }
public List<SelectListItem> BusinessLineList { get; set; }
public string BusinessLine { get; set; }
Solution:
var vm = new ProjectsViewModel()
{
BusinessLineID = 2
};
sp_GetProjectDetails_Result result = db_RIRO.sp_GetProjectDetails(id).FirstOrDefault();
vm.BusinessLineList = db_RIRO.sp_GetAllBusinessLine()
.Select(a => new SelectListItem
{
Value = a.BusinessLineID.ToString(),
Text = a.BusinessLine
})
.ToList();
return PartialView("~/Views/Project/_EditProjDetails.cshtml", vm);
You are looping over all business lines, then creating a list of selectlist items with a value and text for each BusinessLine.
sp_GetProjectDetails_Result result has the single business line id you want selected?
If so, in your loop for each business line, set the select list item's selected property to true if the id is the same as result id from the procedure.
Something like:
Selected = (a.BusinessLineID == result.ID) //or whatever result is from the procedure
I have created a class for that is used to create a reusable dropdown on create/edit views:
public class TimeDropDowns
{
public static int SelectedHour{ get; set; }
public static List<SelectListItem> hours = new List<SelectListItem>()
{
new SelectListItem() {Text="9", Value="09"},
new SelectListItem() {Text="10", Value="10"},
new SelectListItem() {Text="11", Value="11"},
new SelectListItem() {Text="12", Value="12"}
};
}
I am able to display the dropdown 2 ways:
1) in a view #Html.DropDownList("hour", TimeDropDowns.hours, htmlAttributes: new { #class = "form-control" })
2) setting using viewbag in controller ViewBag.hours = TimeDropDowns.hours;
and then referencing in view #Html.DropDownList("hours", null, htmlAttributes: new { #class = "form-control" })
But I haven't been able to set the selected value using either approach, suggestions?
You need to set DropDownList as SelectedHour instead of hours, so that ModelBinder can bind the selected value to SelectedHour when form is posted back to server.
#Html.DropDownList("SelectedHour", ...)
I personally like to use Strongly Typed Model. You can read more here.
The class SelectListItem has a property called Selected. It's type is bool. When this property for an item is true, then it's value is selected.
That being said you need something like this:
public class TimeDropDowns
{
public static List<SelectListItem> GetHoursDropDown(int? selectedHour = null)
{
var items = new List<SelectListItem>();
for(var hour=9; hour<=12; hour++)
{
var hourStr = hour.ToString();
var item = new SelectListItem
{
Text = hourStr,
Value = hour < 9 ? "0"+hourStr : hourStr,
Selected = selectedHour.HasValue && selectedHour == 9
}
items.Add(item);
}
return items;
}
}
Then you could use this as below:
ViewBag.hours = TimeDropDowns.GetHoursDropDown(11);
If you want the selected hour to be the 11th or like:
ViewBag.hours = TimeDropDowns.GetHoursDropDown();
if you want none of them to be selected.
The place of 11, when you post your form, would be taken by the value you post, hour. Apparently this value should be parsed first and the you will pass it to the GetHoursDropDown method.
I strongly encourage you, as already Win have mentioned correctly in his post, to avoid the use of ViewBag and create a strongly type view model.
Thanks to the feedback of the 2 responders I have decided that creating a strongly typed model was the best approach. Since my model was generated from the db I needed to create a partial class so that I would not lose changes if db model refreshed. I created the partial class which is a type of my model class
namespace TouchScreenEvents
{
[MetadataType(typeof(TouchScreenEventMetadata))]
public partial class TouchScreenEvent
{
public string selectedHour { get; set; }
public List<SelectListItem> hours = new List<SelectListItem>()
{
new SelectListItem() {Text="9a", Value="09"},
new SelectListItem() {Text="10a", Value="10"},
new SelectListItem() {Text="11a", Value="11"},
new SelectListItem() {Text="12p", Value="12"},
new SelectListItem() {Text="1p", Value="13"},
new SelectListItem() {Text="2p", Value="14"},
new SelectListItem() {Text="3p", Value="15"},
new SelectListItem() {Text="4p", Value="16"},
new SelectListItem() {Text="5p", Value="17"},
new SelectListItem() {Text="6p", Value="18"},
new SelectListItem() {Text="7p", Value="19"},
new SelectListItem() {Text="8p", Value="20"}
};
public string selectedMinute { get; set; }
public List<SelectListItem> minutes = new List<SelectListItem>()
{
new SelectListItem() {Text="00", Value="00"},
new SelectListItem() {Text="30", Value="30"}
};
}
}
To set the selected index in the controller I have this code (unnecessary parts removed)
//get edit touchscreen event
TouchScreenEvent touchScreenEvent = await db.TouchScreenEvents.FindAsync(id);
var d = touchScreenEvent.date;
touchScreenEvent.selectedMinute= d.ToString("mm");
touchScreenEvent.selectedHour = d.ToString("HH");
And the view code, with previously selected value set. This will also work without the selected index being set - in the create view for instance
#Html.DropDownListFor(model => model.selectedHour, Model.hours, htmlAttributes: new { #class = "form-control" })
#Html.DropDownListFor(model => model.selectedMinute, Model.minutes, htmlAttributes: new { #class = "form-control" })
When posted back to the controller I can access the values like this
touchScreenEvent.selectedHour, touchScreenEvent.selectedMinute
InquiryOrderViewModel
public class InquiryOrderViewModel
{
public InquiryOrder InquiryOrder { get; set; }
public List<InquiryOrderDetail> InquiryOrderDetails { get; set; }
}
InquiryOrderIndex View and the Script to add items
#model eKnittingData.InquiryOrderViewModel
#using (Html.BeginForm("Save", "InquiryOrder"))
{
<div id="editorRows">
#foreach (var item in Model.InquiryOrderDetails)
{
Html.RenderPartial("_DetailEditorRow", item);
}
</div>
#Html.ActionLink("Add another...", null, null, new { id = "addItem" })
<div class="col-md-6"> <input type="submit" value="Save" class="btn btn-success" /> </div>
}
<script>
$('#addItem').click(function (e) {
e.preventDefault();
var isExist = false;
$('.editorRow').each(function () {
if ($(this).children('.class01').val() == 0 || $(this).children('.class02').find("option:selected").text() == "Select") {
isExist = true;
return false;
}
});
if (isExist == false) {
$('.editorRow').each(function () {
$(".editorRow").children().attr("disabled", "disabled");
});
$.ajax({
url: '#Url.Action("BlankEditorRow", "InquiryOrder")',
cache: false,
success: function (data) {
$("#editorRows").append(data);
}
});
}
});
</script>
DetailEditorRow PartialView
#model eKnittingData.InquiryOrderDetail
#using eKnitting.Helpers
#using (Html.BeginCollectionItem("InquiryOrderDetails"))
{
<div class="editorRow">
#Html.DropDownListFor(a => a.ComponentId, (SelectList)ViewBag.CompList, "Select", new { Class = "class02" })
#Html.DropDownListFor(a => a.DesignCodeId, (SelectList)ViewBag.DCodeList, "Select", new { Class = "class03" })
#Html.TextBoxFor(a => a.NoOfParts, new { Class = "class01" })
delete
</div>
}
ActionResult which returns PartialView
public ActionResult BlankEditorRow()
{
var objContext = new KnittingdbContext();
ViewBag.CompList = new SelectList(objContext.Components, "ComponentId", "ComponentName");
ViewBag.DCodeList = new SelectList(objContext.DesignCodes, "DesignCodeId", "DesignCodeCode");
return PartialView("_DetailEditorRow", new InquiryOrderDetail());
}
ActionResult for 'GET'
var objContext = new KnittingdbContext();
var newIovm = new InquiryOrderViewModel();
var newIo = new InquiryOrder();
//initial item
var newIoD = new List<InquiryOrderDetail>
{
new InquiryOrderDetail()
};
newIovm.InquiryOrder = newIo;
newIovm.InquiryOrderDetails = newIoD;
ViewBag.CompList = new SelectList(objContext.Components, "ComponentId", "ComponentName");
ViewBag.DCodeList = new SelectList(objContext.DesignCodes, "DesignCodeId", "DesignCodeCode");
return View(newIovm);
ActionResult for 'POST'
public ActionResult Save(InquiryOrderViewModel inquiryOrderViewModel)
{
.................
}
When i click the add button im able to add items dynamically. But for PostBack it gives me only the lastly appended item. I checked it by putting a break point on post ActionResult. How can i get the whole collection for PostBack? Where did i go wrong? All help appreciated. Thanks!
Your scripts sets a variable var isExist = false;. When you add a new item, you check if the value is false (which it is if you got that far) and then disable all existing inputs.
Disabled form controls do not post back, hence you only get the values for the last row you have added.
Its unclear why you would want to disable them, but if you want to prevent editing of existing rows, the make them readonly
$(".editorRow").children().prop("readonly", true);
Im using asp.net mvc 2. I have a model Supermodel that consists of 2 models TestModel1 and TestModel2.
In SuperModelView Im doing the following thing:
<%: Html.DisplayFor(x=> x.TestModel1, "TestModel1Template") %>
Its working just fine, except for the fact, that dropdownlist is populated but selected value is not set.
Im using the following code for a dropdownlist in my template:
<%: Html.DropDownListFor(x=> x.Property1, (IEnumerable<SelectListItem>)ViewData["MyDDLList"], Model.Property1) %>
and its not setting the selected property. I put the code below to SuperModelView, that calls <%: Html.DisplayFor
To populate the template and it works just fine. So I`m kinda puzzled, what is the difference?
<%: Html.DropDownListFor(x=> x.TestModel1.Property1, (IEnumerable<SelectListItem>)ViewData["MyDDLList"], Model.TestModel1.Property1) %>
UPDATE: I`ve tried to investigate the issue, but something is totally wrong. I can share the whole code, not sure where to put it, here or attach with separate files.
#Darin, what other parts should I share, or just share the whole model view and controller files?
Firstly display templates are just for displaying. If you need to edit with drop down use editor template:
<%: Html.EditorFor(x => x.TestModel1, "TestModel1Template") %>
and in your editor template:
<%: Html.DropDownListFor(x => x.Property1, Model.MyDDLList) %>
where MyDDLList is defined like:
public IEnumerable<SelectListItem> MyDDLList { get; set; }
and in your controller action you fill the values:
public ActionResult Foo()
{
var model = new SuperViewModel
{
TestModel1 = new TestModel1
{
// Set some selected value
Property1 = "1",
// Fill the drop down values
// TODO: use a repository
MyDDLList = new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "text 1" },
new SelectListItem { Value = "2", Text = "text 2" },
new SelectListItem { Value = "3", Text = "text 3" },
}, "Value", "Text")
}
}
return View(model);
}
UPDATE:
Here's a complete working example:
Model:
public class MyViewModel
{
public string SelectedItemId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// Preselect the second item
SelectedItemId = "2",
Items = new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}, "Value", "Text")
};
return View(model);
}
}
View (~/Views/Index.aspx):
<%: Html.DisplayForModel() %>
DisplayTemplate (~/Views/DisplayTemplates/MyViewModel):
<%: Html.DropDownListFor(x => x.SelectedItemId, Model.Items) %>