adding 2 selectList aspMvc - asp.net-mvc

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

Related

How to render database row as html header in mvc 4?

I am doing web application where i have one table. i am making row data as html table header based on id.
This is what i tried. This is controller code.
public ActionResult Index()
{
var table = new List<test> {
new test { Label = "DocumentNumber", Value = "12345678", Emp_id = 1, Name = "First" },
new test { Label = "ExpiryDate", Value = "1/1/2015", Emp_id = 1, Name = "First" },
new test { Label = "DocumentNumber", Value = "123", Emp_id = 2, Name = "Second" },
new test { Label = "ExpiryDate", Value = "1/1/20244", Emp_id = 2, Name = "Second" }
};
var items = table.Where(x => x.Emp_id == 1 || x.Emp_id == 2).ToList();
var headers = items.Select(x => x.Label).Distinct().ToList();
var employers = items.Select(x => x.Emp_id).Distinct().ToList();
if(employers.Count > 1)
headers.Insert(0, "Name");
var data = new List<List<string>>();
data.Add(headers);
foreach (var emp in employers)
{
var row = new List<string>();
foreach (var header in headers)
{
if (header != "Name")
{
var cell = items.Where(x => x.Label == header && x.Emp_id == emp).FirstOrDefault();
row.Add(cell == null ? "" : cell.Value);
}
else
row.Add(items.Where(x => x.Emp_id == emp).First().Name);
}
data.Add(row);
}
return View(data);
}
This is view code
#model List<List<string>>
<table>
<thead>
<tr>
#foreach (var header in Model.First())
{
<th>#header</th>
}
</tr>
</thead>
<tbody>
#foreach (var row in Model.Skip(1))
{
<tr>
#foreach (var cell in row)
{
<td>#cell</td>
}
</tr>
}
</tbody>
</table>
Now i am able to render as below.
Name DocumentNumber ExpiryDate
First 12345678 1/1/2015
Second 123 1/1/20244
But i want header to be appeared for each row of data. For example if i add one more header Issueddate for Emp_id 2(i hardcoded at the begining) the output should look like below.
Name DocumentNumber ExpiryDate
First 12345678 1/1/2015
Name DocumentNumber ExpiryDate Issueddate
Second 123 1/1/20244 1/1/2015
So in the above code where i should make changes to appear headers for each row of data? Hope you clearly understood the scenario. Thanks in advance. i tried as you said but header appends to each row of data as below.
Name DocumentNumber ExpiryDate Issueddate
First 12345678 1/1/2015
Name DocumentNumber ExpiryDate Issueddate
Second 123 1/1/20244 1/1/2015
now issued date should come for only emp_id with 2? Hope you understood.
This is my code.
var table = new List<test> {
new test { Label = "DocumentNumber", Value = "12345678", Emp_id = 1, Name = "First" },
new test { Label = "ExpiryDate", Value = "1/1/2015", Emp_id = 1, Name = "First" },
new test { Label = "DocumentNumber", Value = "123", Emp_id = 2, Name = "Second" },
new test { Label = "ExpiryDate", Value = "1/1/20244", Emp_id = 2, Name = "Second" },
new test { Label = "Issuedon", Value = "1/1/20244", Emp_id = 2, Name = "Second" }
With respect to above data i want output like this below.
Name DocumentNumber ExpiryDate
First 12345678 1/1/2015
Name DocumentNumber ExpiryDate Issueddon
Second 123 1/1/20244 1/1/20244
Move the first loop to inside the second loop
<table>
<tbody>
<tr>
#for (int i = 1; i < Model.Count; i++)
{
foreach (var header in Model.First())
{
if (header == "Issuedon")
{
if (!string.IsNullOrEmpty(Model[i][3])) //assuming issue date will be at 3rd index , thoug this approch is not good as OP send model as List of string not model which is a ideal option
{
<th>#header
</th>
}
else
{
continue;
}
}
else
{
<th>#header
</th>
}
}
<tr>
#foreach (var cell in Model[i])
{
<td>#cell
</td>
}
</tr>
}
</tr>
</tbody>
SIDE NOTE : assuming issue date will be at 3rd index , though this approach is not good But there is no other option as OP send model as List of string not model which should be an ideal option

Displaying values in ListBox based on Dropdoown values

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

Get Selected Value of Dropdownlist in ActionLink (MVC 5)

I am trying to get the selected value of a dropdownlist in #Html.ActionLink but no luck so far. Requirement is to dynamically retrieve a table and have a dropdown list for actions that can be taken against the row. I need to select an action and then on hitting submit button, row ID and selected action value should be posted to the controller. Here is the piece of code I have in place.
#foreach (AdsViewModel ad in Model)
{
<tbody>
<tr>
<td>#ad.Row_Id</td>
<td class=" "> #ad.Description </td>
<td class=" "> #ad.Valid_To.ToShortDateString() </td>
<td><span class="label label-sm label-success label-mini"> #ad.Status </span></td>
<td>#Html.DropDownList("actions", ad.Actions) </td>
<td>#Html.ActionLink("Submit", "AdAction", new {adId = ad.Row_Id, action = ad.Actions.SelectedValue}) </td>
</tr>
</tbody>
}
On clicking the Submit ActionLink, I am getting the adId but no action is returned from the dropdownlist.
Your help is much appreciated.
Edit: Here is the AdsViewModel
public class AdsViewModel
{
public string Row_Id { get; set; } //Transaction Number
public string Description { get; set; } //Trasaction Description
public DateTime Valid_To { get; set; } //Expiry
public string Status { get; set; } //Object Status Code
public SelectList Actions { get; set; }
}
This is how the Select list is filled in Controller
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = "View", Value = "001" });
items.Add(new SelectListItem(){Text = "Modify", Value = "002"});
model.Actions = items;
This line
<td>#Html.ActionLink("Submit", "AdAction", new {adId = ad.Row_Id, action = ad.Actions.SelectedValue}) </td>
is setting the route value action to the selected value at the time the view is created on the server and before its sent to the browser (the user hasn't selected anything yet so its null). If you are wanting to set the value to "001" or "002" (the values of the dropdowns), then you need to use javascript update the href attribute of the link when the dropdown changes. An easier and more conventional solution would be to delete the dropdown and use 2 action links, one for Viewand one for Edit. Since they are 2 different actions, there should also be 2 seperate ActionResult methods in your controller. For example
#Html.ActionLink("View", "View", new { id = ad.Row_Id }) // calls the View method
#Html.ActionLink("Modify", "Modify", new { id = ad.Row_Id }) // calls the Modify method
Edit
To do this using javascript, delete the #Html.ActionLink and replace with a <button type="button"> or other element and handle its click event
var url = '#Url.Action("AdAction")';
$('button').click(function() {
var row = $(this).closest('tr');
var rowID = row.children('td').eq(0).text();
var actionID = row.find('select').val();
window.location.href = url + '?adId=' + rowID + '&action=' + actionID;
});
Note: You are creating invalid html with the #Html.DropDownList() method (all <selects> will have id="action")
This should fix it...
#for (int i = 0; i < Model.Count(); i++)
{
var ad = Model[i];
<tbody>
<tr>
<td>#ad.Row_Id</td>
<td class=" "> #ad.Description </td>
<td class=" "> #ad.Valid_To.ToShortDateString() </td>
<td><span class="label label-sm label-success label-mini"> #ad.Status </span></td>
<td>#Html.DropDownListFor("actions", m => m[i].Actions) </td>
<td>#Html.ActionLink("Submit", "AdAction", new {adId = ad.Row_Id, action = ad.Actions.SelectedValue}) </td>
</tr>
</tbody>
}
Thank you Everyone, I solved it by writing a Javascript function and calling that function on the onClink Event of the button.
<script type="text/javascript" language="javascript">
function ShowEditData() {
var url = '#Url.Action("AdAction")';
var rows = document.getElementById("mytable").rows;
for (var i = 0, ceiling = rows.length; i < ceiling; i++) {
rows[i].onclick = function () {
debugger;
var Row_Id = this.cells[0].innerHTML;
var actionID = this.cells[4].childNodes[0].value;
window.location.href = url + '?row_id=' + Row_Id + '&action_id=' + actionID;
}
}
}
</script>

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...

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