Displaying values in ListBox based on Dropdoown values - asp.net-mvc

In my view I have one dropdown Role and second ListBox as Permissions. I want to change the values in ListBox as User selects the values in Dropdown Role
<tr>
<td>#Html.Label("","Role")</td>
<td>#Html.DropDownListFor(x => x.Role, #ViewBag.role as SelectList, new { #class = "dropdown"} )</td>
</tr>
<tr>
<td>#Html.Label("","Permissions in Role")</td>
<td>#Html.ListBox("permissions", #ViewBag.permissions as SelectList, new { #class = "chosen-select", data_placeholder = "Add Permissions to Role...", style = "width:500px;", tabindex = "4"})</td>
</tr>
In My js file (Updated After Stephen Suggestion)
$(document).on('change', '#Role_RefID', function () {
var selection = $(this).val();
$.getJSON(window.location.pathname + "/getPermissions?id="+selection, function (result) {
var ddl = $('#permissions');
ddl.empty().trigger("chosen:updated");
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl)
.attr('selected',"selected")
;
});
ddl.trigger("chosen:updated");
});
});
getPermissions (Updated after Stephen Suggestion)
public JsonResult getPermissions(int id)
{
List<Reference> perms = rep.permsInRole(id);
var res = perms.Select(p => new { Id = p.RefID, Value = p.Description }).Distinct().ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
ListBox displays the initial values from DB but when I change the values in dropdown It doesnt clear the contents of Listbox and also doesnt display the new values in ListBoxListBox

Related

adding 2 selectList aspMvc

I've got two ViewBag there and I would like to make one
in that way I can get the 2 different address of the customer shown in one DropDownList
....
var customerAdress = from cl2 in dc.Adresses
where cl2.Customer.User.UserEmail == User.Identity.Name
select cl2;
var Adresses = new SelectList(customerAdress.ToList(), "AdressID", "AdressLine1 ", null);
var Adresses2 = new SelectList(customerAdress.ToList(), "AdressID", "AdressLine2", null);
....
there is my View:
....
<tr>
<td>Address</td>
<td colspan="3">
#Html.DropDownList("Adresses", (IEnumerable<SelectListItem>)(ViewBag.Adresses))
</td>
</tr>
.....
You would need to concatenate them to be shown in one dropdown list like:
var addressesList = customerAdress
Select(x=> new
{
ID = x.AddressID,
AddressLine = x.AddressLine1 + x.AddressLine2
});
ViewBag.Adresses = new SelectList(addressesList.ToList() , "AdressID", "AddressLine ", null);
and do not set the DropDownList helper name same as your ViewBag key, they should be different to prevent unexpected behaviors.
And in view do like:
#Html.DropDownList("SelectAddress",ViewBag.Adresses as SelectList,"Select Address")
When you set the name of the DropDownList helper to be the same as ViewBag key it will look for a key in the ViewBag for populating the DropDownList items, in that case you would need to just specify name to be same as ViewBag key:
Html.DropDownList("Adresses","Select Address")
Hope it helps!
my question wasn't clear it contained already a try of solution which may have mislead all the solution i've got
so here my solution i just used Group property on SelectListItem
my controller
....
var customerAdress = from cl2 in dc.Adresses
where cl2.Customer.User.UserEmail == User.Identity.Name
where cl2.Commands.FirstOrDefault().DeliveryAdressID==cl2.AdressID
select cl2;
var addressesList = customerAdress.
Select(x => new
{
ID = x.AdressID,
AddressLine = x.AdressLine1
});
var addressesList2 = customerAdress.
Select (x => new
{
ID = x.AdressID,
AddressLine = x.AdressLine2
}) ;
var allAdress = new List<SelectListItem>();
var group1 = new SelectListGroup() { Name = "DeliverableAdress" };
foreach (var item in addressesList)
{
allAdress.Add(new SelectListItem() { Text = item.AddressLine, Group = group1 });
}
foreach (var item in addressesList2)
{
allAdress.Add(new SelectListItem() { Text = item.AddressLine, Group = group1 });
}
//var Adresses = new SelectList(addressesList.ToList(), "AdressID", "AddressLine ", null);
ViewBag.allAdress = allAdress;
....
and my view
....
<tr>
<td>Address</td>
<td colspan="3">
#Html.DropDownList("allAdress", (IEnumerable<SelectListItem>)ViewBag.allAdress)
</td>
</tr>
....
but actually i misunderstood it the right idea is t concatenate the 2 adresslines because it's just details of one address and no 2 address as i thought

Simple Dropdown list in Edit MVC 4

I have simple table with users, which have edit column, so when you click it, you can edit this specific row. One of columns in my tables is TimeZone, so you can choose in which time zone you are. So proper way to create edit filed is Dropdown list.
So I find this code and implemented it in my controller:
public ActionResult Edit(int id = 0)
{
using (var dbVn = new userDbEntities())
{
var edit = dbVn.UsersTables.Find(id);
if (edit == null)
{
return HttpNotFound();
}
SelectListItem item;
var zoneList = new List<SelectListItem>();
item = new SelectListItem();
item.Text = "TimeZone1";
item.Value = "1";
zoneList.Add(item);
item = new SelectListItem();
item.Text = "TimeZone2";
item.Value = "2";
zoneList.Add(item);
ViewBag.ZoneT = zoneList;
return View(edit);
}
}
And in my view I have this:
<div class="editor-field">
#Html.DropDownListFor(model => model.TimeZoneId, new SelectList((IEnumerable<SelectListItem>)ViewBag.ZoneT, "Value", "Text", "1"))
#Html.ValidationMessageFor(model => model.TimeZoneId)
</div>
This works fine if we would have a few items (3 to 4). But if we have a list of timezonese (96), is proper to use datatable (TimeZoneTable).
Any Idea how to implement it in above code in controller...

Dynamic state city drop down list in mvc using jquery

i am adding values to 2 dropdownlists dynamically ,to the state dropdownlist it is populated during form load and to the city it must be populated when the jquery fires out when the user clicks on any state,the problem i am facing is that,the state dropdownlist is easily populated but the city dropdownlist does not contain any values when i select a particular state,
the state and city are strings stored in a table in my db
i ll post my code below so that if anyone can sort out what is wrong with my code
homecontroller
public ActionResult registration()
{
ViewBag.states = dd.tb_statecities.Select(m => new SelectListItem { Text=m.state}).Distinct().ToList();
return View();
}
public ActionResult get(string state)
{
var v = (dd.tb_statecities.Where(m => m.state == state).Select(m => m.city)).ToList();
return Json(v, JsonRequestBehavior.AllowGet);
}
jquery..
$(function () {
$('#states').change(function () {
var val = $('#states').val();
$.get("home/get", { state: val }, function (data) {
var v = "<option>Select</option>"
$.each(data, function (i, q) {
alert("hello");
v += "<option value=" + q + ">" + q + "</option>";
});
$('#city').html(v);
});
});
});
registration.cshtml
State #Html.DropDownList("states","Select")
</tr>
<tr class="t">
<td>City</td>
<td>#Html.DropDownList("city", new List<SelectListItem> { new SelectListItem{Text="Select",Value="0"}})</td>
</tr>
The problem is you didn't send value/id when you use ViewBag,
I suggest you use SelectList in your ViewBag :
ViewBag.states = new SelectList(db.states, "ID", "states");
Then you can get the value from using JQuery :
var val = $('#states').val();

Drop down list doesnt show the selected value in edit mode in mvc 2

Hi I am trying to display the database value on the dropdownlist in the edit section, but the drop down list shows the default set value below is my code:
Controller:
public ActionResult Edit(int id)
{
// Product helmet = new Product();//
//Product garrage = new Product();
ViewBag.mode = "edit";
// for dropdown track
ITrackRepository trackResp = new TrackRepository();
IQueryable<Object> tracks = trackResp.GetVenuesSelectlist();
ViewData["Venue"] = new SelectList(tracks, "VenueID", "Name");
// for dropdown for event type
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<EventType> eventTypes = trackdayResp.GetAllEventTypes();
ViewData["EventTypes"] = new SelectList(eventTypes, "ID", "Name");
// for dropdown experience
IExperienceLevelRepository expLevelResp = new ExperienceLevelRepository();
IQueryable<ExperienceLevel> expLevel = expLevelResp.GetAllExperienceLevels().OrderBy(ExperienceLevel => ExperienceLevel.Name);
ViewData["Experience"] = new SelectList(expLevel, "ID", "Name");
// dropdown for helmets
IProductRepository prodResp = new ProductRepository();
Product productQuantity = prodResp.GetProd(id);
if (productQuantity.ProductTypeID == 1)
{
// dropdown for attendees
var attendees = Enumerable.Range(1, 80).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text",**productQuantity.QtyAvailable)**; //productQuantity.QtyAvailable is the value from db(selected value of dropdown)
ViewData["txtAttendees"] = productQuantity.UnitCost;
}
else
{
var emptyattendees = Enumerable.Range(1, 80).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
ViewData["attendees1"] = new SelectList(emptyattendees.ToList(), "Value", "Text");
} Event trackday = trackdayResp.GetEvent(id); //returns all the values from event table whose eventid is id
//need to return product quantity, value to drop downlist
return View("Create", trackday);
}
View Edited(WOrking):
<% if (ViewBag.mode != "edit")
{ %>
<%: Html.DropDownList("attendees1", ViewData["attendees1"] as SelectList, "--select--")%>
<%}else{%>
<%: Html.DropDownList("attendees1")%>
<%} %>
I had the same problem a month ago, and I solved it by doing this:
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text", productQuantity.QtyAvailable);
I mean, you have to add a 4th parameter with the SelectedValue which you take it from the original value before the edit. You have to do this only in Edit action, no need to do that in Create since it is a new object and no value is selected yet.
And in your markup you define the DropDownList like this:
<%: Html.DropDownList("attendees1") %>
This way the selected value will be selected instead of the default one.
Hope that helps.
EDIT:
Create action method:
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text");
Edit action method:
ViewData["attendees1"] = new SelectList(attendees, "Value", "Text", productQuantity.QtyAvailable);
Markup in both Create and Edit views
<%: Html.DropDownList("attendees1") %>

How to make dropdownlist show a selected value in asp.net mvc?

I have an edit page with a Html.DropDownList in it....I cant show the dropdownlist value it always shows up with Select instead i want to make the dropdown show an item as selected based on a model value say Model.Mes_Id... Any suggestion how it can be done...
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType", // what should i give here?)%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
EDIT: It has the list items but i want to show a value selected in the edit view...
public ActionResult Edit(int id)
{
var mesurementTypes = consRepository.FindAllMeasurements();
ViewData["MeasurementType"] = mesurementTypes;
var material = consRepository.GetMaterial(id);
return View("Edit", material);
}
My repository method,
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
Set the selected item when you create the IEnumerable<SelectListItem>.
Personally I would create a specialized viewmodel for the form but going by your code, do something like:
public ActionResult Edit(int id)
{
//Put this first
var material = consRepository.GetMaterial(id);
//pass in your selected item
var mesurementTypes = consRepository.FindAllMeasurements(material.MeasurementTypeId);
ViewData["MeasurementType"] = mesurementTypes;
return View("Edit", material);
}
Then change your repository method to something like:
public IEnumerable<SelectListItem> FindAllMeasurements(int selectedId)
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name,
Selected = mt.Id == selectedId
};
return mesurements;
}
HTHs,
Charles
Have a look at this blog entry.
http://weblogs.asp.net/ashicmahtab/archive/2009/03/27/asp-net-mvc-html-dropdownlist-and-selected-value.aspx
Basically, you need to convert your mesurementTypes list/enumerable into a SelectList or IEnumerable<SelectListItem>.
I would recommend, if possible, upgrading to ASP.NET MVC2 and using Html.DropDownListFor()
You should be returning a SelectionList which can specify a selected item.
How to create a DropDownList with ASP.NET MVC
Assuming that Model.Mes_Id contais the selected value, you can do something like this
<%
var Measurements = new SelectList((IEnumerable)ViewData["MeasurementType"], "Id", "Name", Model.Mes_Id);
Response.Write(Html.DropDownList("measurement_type", Measurements, "Select"));
%>
Html.DropDownListFor didn't work for me So I got the poppy like this
(in Edit method )
CreatList(long.Parse(wc.ParentID.ToString()));
private void CreatList(long selected= 0)
{
SqlConnection conn = new SqlConnection(Config.ConnectionStringSimple);
conn.Open();
Category wn = new Category(conn);
CategoryCollection coll = new CategoryCollection();
Category.FetchList(conn, ref coll);
ViewBag.ParentID = GetList(coll, selected);
}
private List<SelectListItem> GetList(CategoryCollection coll, long selected)
{
List<SelectListItem> st = new List<SelectListItem>();
foreach (var cat in coll)
{
st.Add( new SelectListItem
{
Text = cat.Name,
Value = cat.ID.ToString(),
Selected = cat.ID == selected
});
}
SelectListItem s = new SelectListItem {
Text = Resources.lblSelect,
Value = "0"
};
st.Insert(0, s);
return st;
}
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("ddlCat", (List<SelectListItem>)ViewBag.ParentID)
#Html.ValidationMessageFor(model => model.ParentID)
</div>

Resources