At the moment I have a drop down box which only displays a Suppliers Name with the value of the ID hidden behind it. I would also like to display the Suppliers account number next to the Supplier Name.
HTML:
#Html.DropDownListFor(
m => m.SupplierID,
new SelectList(Model.Suppliers, "SupplierID", "SupplierName"),
new { #id = "SuppNameDD", #class = "GRDropDown" }
)
Controller:
public ActionResult Index(string client) {
int clientID = clientRepo.GetClientIDByName(client);
DashboardViewModel model = new DashboardViewModel();
model.ClientID = clientID;
model.ClientName = client;
model.FinancialsAtAGlance = reportRepo.GetFinancialsAtAGlance(model.ClientID);
model.SupplierID = -1;
model.AccountNo = null;
model.Suppliers = supplierRepo.GetAllSuppliersByClient(clientID);
model.ReviewID = -1;
model.AccountNo = null;
model.Reviews = reviewRepo.GetAllReviewsByClientID(clientID);
return View(model);
}
ViewModel:
public class DashboardViewModel {
public int ClientID { get; set; }
public string ClientName { get; set; }
public IQueryable<FinancialsAtAGlanceModel> FinancialsAtAGlance { get; set; }
public Dictionary<string, Dictionary<string, decimal?>> Budgets { get; set; }
public class SelectReport {
public int ReportID { get; set; }
public string ReportType { get; set; }
public static IEnumerable<SelectReport> Reports = new List<SelectReport> {
new SelectReport {
ReportID = 1,
ReportType = "Claims By Supplier"
},
new SelectReport {
ReportID = 2,
ReportType = "Department breakdown"
},
new SelectReport {
ReportID = 3,
ReportType = "Reason Code breakdown"
},
new SelectReport {
ReportID = 4,
ReportType = "Monthly Debiting report"
}
};
}
public List<SelectReport> allReports { get; set; }
public int SupplierID { get; set; }
public IEnumerable<Supplier> Suppliers { get; set; }
public int ReviewID { get; set; }
public string AccountNo { get; set; }
public IEnumerable<Review> Reviews { get; set; }
}
How can add this is as the other value is a selected value and this is not what I want. It should be another datatext field.
If this display name is something that would be used multiple times, I would suggest adding a property to your Supplier class. Something like DisplayName:
public class Supplier
{
//...
public string SupplierName { get; set; }
public string AccountNumber { get; set; }
//...
public string DisplayName
{
get { return String.Format("{0} ({1})", SupplierName, AccountNumber); }
}
}
Then, you just need to change your drop down list to use DisplayName instead of SupplierName as the text field:
#Html.DropDownListFor(m => m.SupplierID, new SelectList(Model.Suppliers, "SupplierID", "DisplayName"), new { #id = "SuppNameDD", #class = "GRDropDown" })
EDIT:
There is another way to do this that can be done all in the view:
#Html.DropDownListFor(m => m.SupplierID, Model.Suppliers.Select(item => new SelectListItem
{
Value = item.SupplierID.ToString(),
Text = String.Format("{0} ({1})", item.SupplierName, item.AccountNumber.ToString()),
Selected = item.SupplierID == Model.SupplierID
}))
Probably you can achieve your desired output by 1.create a custom helper with with extension method which will return MvcHtmlString which will create your custom HTML for dropdown and call that method in your view.
Like Below
public static class CustomDropdown
{
public static string Dropdown(Priority priority)
{
StringBuilder sb=new StringBuilder ();
sb+="<Select id='drop'>";
for(int i=0;i<priority.name.length;i++)
{
sb+="<option id='dropop' value='"+priority.value[i]+"'title='"+priority.title[i]+"'>"+priority.name[i]+"</option>";
}
sb+="</select>";
return Convert.ToString(sb);
}
}
2.Bind the options of the given select with help of jquery like
var i=0;
$('.drpclass option').each(function(){
$(this).attr('title',Model.priority.title[i])
i++;
});
Related
I have this models
public class RoutingAttributeModel
{
public int Bus_No { get; set; }
public int Attribute_No { get; set; }
public string Attribute_Name { get; set; }
public string Status { get; set; }
public string Notes { get; set; }
}
public class AgentRoutingAttributeModel
{
public int Agent_No { get; set; }
public int Bus_No { get; set; }
public int Attribute_No { get; set; }
public string Attribute_Name { get; set; }
public string Status { get; set; }
}
List<RoutingAttributeModel> lstComplete = new List<RoutingAttributeModel>();
List<AgentRoutingAttributeModel> lstAssigned = new List<AgentRoutingAttributeModel>();
Filled this with some data
Is it possible to filter with Linq? I want to save in a new list the diferent content between lstComplete and lstAssigned
I was trying to join both lists but got stuck there
var results1 = from cl in lstComplete
join al in lstAssigned
on cl.Attribute_No equals al.Attribute_No
select cl;
you can use linq
as my understanding, you try to find linked by attribute_No records and have a list of not matching properties?
lstComplete.Add(new RoutingAttributeModel(){
Attribute_Name = "aaa",
Attribute_No = 1,
Bus_No = 1,
Notes = "",
Status = "status"
});
lstAssigned.Add(new AgentRoutingAttributeModel()
{
Attribute_No = 1,
Agent_No = 10,
Bus_No = 1,
Attribute_Name = "bbb",
Status = "status2"
});
var lst = lstComplete
.Join(lstAssigned,
complete => complete.Attribute_No,
assigned => assigned.Attribute_No,
(complete, assigned) => new { lstComplete = complete, lstAssigned = assigned })
.Select(s => new { s.lstComplete, s.lstAssigned})
.Where(w=>
w.lstAssigned.Attribute_Name != w.lstComplete.Attribute_Name
|| w.lstAssigned.Bus_No != w.lstComplete.Bus_No
)
.ToList()
.Dump();
so result would be
You could try the following query
var filteredList = lstComplete
.Where(x => !lstAssigned.Any(y => y.Attribute_No == x.Attribute_No));
I'm developing an ASP.NET MVC 5 application, with C# and .NET Framework 4.6.1.
I have this View:
#model MyProject.Web.API.Models.AggregationLevelConfViewModel
[...]
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, (SelectList)Model.HelperCodeTypeItems, new { id = "Configurations[0].HelperCodeType" })
The ViewModel is:
public class AggregationLevelConfViewModel
{
private readonly List<GenericIdNameType> codeTypes;
private readonly List<GenericIdNameType> helperCodeTypes;
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
public int ProductionOrderId { get; set; }
public string ProductionOrderName { get; set; }
public IList<Models.AggregationLevelConfiguration> Configurations { get; set; }
public AggregationLevelConfViewModel()
{
// Load CodeTypes to show it as a DropDownList
byte[] values = (byte[])Enum.GetValues(typeof(CodeTypes));
codeTypes = new List<GenericIdNameType>();
helperCodeTypes = new List<GenericIdNameType>();
for (int i = 0; i < values.Length; i++)
{
GenericIdNameType cType = new GenericIdNameType()
{
Id = values[i].ToString(),
Name = EnumHelper.GetDescription((CodeTypes)values[i])
};
if (((CodeTypes)values[i]) != CodeTypes.NotUsed)
codeTypes.Add(cType);
helperCodeTypes.Add(cType);
}
}
}
And Models.AggregationLevelConfiguration is:
public class AggregationLevelConfiguration
{
public byte AggregationLevelConfigurationId { get; set; }
public int ProductionOrderId { get; set; }
public string Name { get; set; }
public byte CodeType { get; set; }
public byte HelperCodeType { get; set; }
public int PkgRatio { get; set; }
public int RemainingCodes { get; set; }
}
I need to set selected value in these properties:
public IEnumerable<SelectListItem> CodeTypeItems
{
get { return new SelectList(codeTypes, "Id", "Name"); }
}
public IEnumerable<SelectListItem> HelperCodeTypeItems
{
get { return new SelectList(helperCodeTypes, "Id", "Name"); }
}
But I can't set it in new SelectList(codeTypes, "Id", "Name"); or new SelectList(helperCodeTypes, "Id", "Name"); because the selected value are in Configurations array: fields AggregationLevelConfiguration.CodeType and AggregationLevelConfiguration.HelperCodeType.
I think I have to set selected value in the View, but I don't know how to do it.
How can I set the selected values?
Unfortunately #Html.DropDownListFor() behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate)
Create a custom EditorTemplate for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml (note the name must match the name of the type
#model yourAssembly.AggregationLevelConfiguration
#Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList to the EditorTemplate as additionalViewData
#using (Html.BeginForm())
{
...
#Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList in each iteration and set the selectedValue)
In this option your property CodeTypeItems should to be IEnumerable<GenericIdNameType>, not a SelectList (or just make codeTypes a public property). Then in the main view
#Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType" - the DropDownListFor() method already generated that id attribute
I wrote this class to overcome an issue I was having with selecting an option in an html select list. I hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Login_page.Models
{
public class HTMLSelect
{
public string id { get; set; }
public IEnumerable<string> #class { get; set; }
public string name { get; set; }
public Boolean required { get; set; }
public string size { get; set; }
public IEnumerable<SelectOption> SelectOptions { get; set; }
public HTMLSelect(IEnumerable<SelectOption> options)
{
}
public HTMLSelect(string id, string name)
{
this.id = id;
this.name = name;
}
public HTMLSelect(string id, string name, bool required, IEnumerable<SelectOption> options)
{
this.id = id;
this.name = name;
this.required = required;
}
private string BuildOpeningTag()
{
StringBuilder text = new StringBuilder();
text.Append("<select");
text.Append(this.id != null ? " id=" + '"' + this.id + '"' : "");
text.Append(this.name != null ? " name=" + '"' + this.name + '"' : "");
text.Append(">");
return text.ToString();
}
public string GenerateSelect(IEnumerable<SelectOption> options)
{
StringBuilder selectElement = new StringBuilder();
selectElement.Append(this.BuildOpeningTag());
foreach (SelectOption option in options)
{
StringBuilder text = new StringBuilder();
text.Append("\t");
text.Append("<option value=" + '"' + option.Value + '"');
text.Append(option.Selected != false ? " selected=" + '"' + "selected" + '"' + ">" : ">");
text.Append(option.Text);
text.Append("</option>");
selectElement.Append(text.ToString());
}
selectElement.Append("</select");
return selectElement.ToString();
}
}
public class SelectOption
{
public string Text { get; set; }
public Boolean Selected { get; set; }
public string Value { get; set; }
}
}
And
public IEnumerable<SelectOption> getOrderTypes()
{
List<SelectOption> orderTypes = new List<SelectOption>();
if (this.orderType == "OptionText")
{
orderTypes.Add(new SelectOption() { Value = "1", Text = "OptionText", Selected = true });
} else
{
orderTypes.Add(new SelectOption() { Value = "2", Text = "OptionText2" });
}
}
And to use it:
#{
Login_page.Models.HTMLSelect selectElement = new Login_page.Models.HTMLSelect("order-types", "order-types");
}
#Html.Raw(selectElement.GenerateSelect(Model.getOrderTypes()));
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
We had in a view this line at the top:
IEnumerable<SelectListItem> exitFromTrustDeed = (ViewData["ExitFromTrustDeed"] as IEnumerable<string>).Select(e => new SelectListItem() {
Value = e,
Text = e,
Selected = Model.ExitFromTrustDeed == e
});
and then below in the view:
#Html.DropDownListFor(m => m.ExitFromTrustDeed, exitFromTrustDeed, new { #class = "form-control" })
We had a property in my ViewData with the same name as the selector for the lambda expression and for some reason that makes the dropdown to be rendered without any option selected.
We changed the name in ViewData to ViewData["ExitFromTrustDeed2"] and that made it work as expected.
Weird though.
I am new to ASP.NET. My form look like this
This code display role in Form
#Html.DropDownList("id", (IEnumerable<SelectListItem>)ViewBag.lis, null, new { #class = "form-control" })
in Controller
public ActionResult register()
{ //
ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "id", "name");
return View();
}
ROLE CLASS
public partial class Role
{
public int Id { get; set; }
public string name { get; set; }
public virtual Register Register { get; set; }
}
Register class
public partial class Register
{
public int Id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string password { get; set; }
public Nullable<int> phone_no { get; set; }
public virtual Role Role { get; set; }
}
The problem is that I can get all data except for Role. The role is null. How do I get the Role ID?
[HttpPost]
public ActionResult register(Register obj)
{
using(var db = new dbdemoEntities())
{
var data = new Register()
{
email = obj.email,
name = obj.name,
password = obj.password,
phone_no = obj.phone_no,
Role = obj.Role
};
db.Registers.Add(data);
db.SaveChanges();
ViewBag.register = "Your account has been registered!";
}
return PartialView();
}
I think the problem is that I should write model => model.role like the example of the name here.
#Html.EditorFor(model => model.name, new { htmlAttributes = new { #class = "form-control" } })
here is what I updated now
ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "Id", "name");
In HTML
Problem after update:
After changing
Role = db.Roles.Single(r => r.Id == obj.Role.Id)
Here is another error
Try this:
Change: ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "id", "name");
to
ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "Id", "name");
and then:
#Html.DropDownList(model => model.Role.Id, (IEnumerable<SelectListItem>)ViewBag.lis, null, new { #class = "form-control" })
and also make a constructor for Register class:
public partial class Register
{
public Register()
{
this.Role = new Role();
}
public int Id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string password { get; set; }
public Nullable<int> phone_no { get; set; }
public virtual Role Role { get; set; }
}
====== Update =======
Change the action like this:
[HttpPost]
public ActionResult register(Register obj)
{
using(var db = new dbdemoEntities())
{
var data = new Register()
{
email = obj.email,
name = obj.name,
password = obj.password,
phone_no = obj.phone_no,
Role = db.Roles.Single(r=> r.Id == obj.Role.Id)
};
db.Registers.Add(data);
db.SaveChanges();
ViewBag.register = "Your account has been registered!";
}
return PartialView();
}
Change to this this if you want to post Register.Id property:
#Html.DropDownListFor(model => model.Id,(SelectList) ViewBag.list,new { #class="form-control"})
I'm working with KnockoutMVC and it requires strongly type models to use inside the VIEW. I have tried multiple variations of the examples on KnockoutMVC's site including using ENUMS and still could not get it to work. Perhaps this is a problem with the setup of my models.
MODELS
public class PhoneNumber
{
public List<NumberTypeClass> Types { get; set; }
//public NumberType enumType { get; set; }
//public enum NumberType
//{
// Work,
// Home,
// Mobile,
// Fax
//}
private string _number;
[StringLength(14, MinimumLength = 10, ErrorMessage = "Please use (123) 456-7890 format"), Required]
public string Number
{
get
{
this._number = BeautifyPhoneNumber(this._number);
return this._number;
}
set
{
this._number = value;
}
}
public string Extension { get; set; }
public static String BeautifyPhoneNumber(string numberToBeautify)
{
//beautifyNumberCode
}
}
public class NumberTypeClass
{
public int Id { get; set; }
public string NumberType { get; set; }
}
public class VendorsEditorVendorModel
{
public string FirstName {Get;set;}
public string LastName {get;set;}
public List<Address> Address {get;set;}
public List<PhoneNumber> Phones {get;set;}
}
public class VendorsEditorModel
{
public List<VendorsEditorVendorModel> Vendors {get;set;}
}
CONTROLLER
public class VendorsEditorController : BaseController
{
public ActionResult CreateVendors()
{// VendorsEditor/CreateVendors
var vendor = new VendorsEditorModel();
vendor.Vendors = new List<VendorsEditorVendorModel>();
vendor.Vendors[0].Phones[0].Types = new List<NumberTypeClass>
{
new NumberTypeClass{Id = 0, TypeName = "Mobile"},
new NumberTypeClass{Id = 0, TypeName = "Work"},
new NumberTypeClass{Id = 0, TypeName = "Home"}
};//this throws an error because there is no Vendors[0] ...but how would i populate this list for every Vendor?
return View(vendor);
}
}
You cannot call an empty collection by index [x]. You need to fill your collection from a database or what not before you can access items in it. If you are just trying to add items to a collection, this is how you do it:
var vendor = new VendorsEditorModel
{
Vendors = new List<VendorsEditorVendorModel>
{
new VendorsEditorVendorModel
{
Phones = new List<PhoneNumber>
{
new PhoneNumber
{
Types = new List<NumberTypeClass>
{
new NumberTypeClass {Id = 0, NumberType = "Mobile"}
}
}
}
}
}
};
If you just want to add the types to an already populated collection, you can do the following:
foreach (var phone in vendor.Vendors.SelectMany(item => item.Phones))
{
phone.Types = new List<NumberTypeClass>
{
new NumberTypeClass{Id = 0, NumberType = "Mobile"},
new NumberTypeClass{Id = 0, NumberType = "Work"},
new NumberTypeClass{Id = 0, NumberType = "Home"}
};
}
This is my model class:
public class EstimateModel:estimate
{
public string EstimateNo { get; set; }
//public SelectList Customer { get; set; }
//[DisplayName("Customer ID :")]
public int CustID { get; set; }
[DisplayName("Customer Name :")]
public string CustFname { get; set; }
[DisplayName("Company Name :")]
public string CompanyName { get; set; }
[DisplayName("Total:")]
public decimal total { get; set; }
[DisplayName("Tax1 :")]
public decimal tax1 { get; set; }
public decimal tax2 { get; set; }
public decimal tax3 { get; set; }
public decimal subtot { get; set; }
[DisplayName("Discount :")]
public decimal Discount { get; set; }
[DisplayName("GrandTotal:")]
public decimal grandtotal { get; set; }
public List<estimate> estimates { get; set; }
public EstimateModel()
{
estimates = new List<estimate>();
}
}
This is my controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EstimateModel employee)
{
//employee.Customer= new SelectList("CustID","CustFName");
DataTable dt = new DataTable();
//for (int i = 0; i < employee.estimates.Count; i++)
//{
// total = total + employee.estimates[i].Amount;
//} ViewBag.Message = total;
//Skill abc = new Skill();
var sys = db.EstimateMasters.Create();
// var user = db.Adils.Create();
sys.EstimateNo = employee.EstimateNo;
for(int i=0 ;i<employee.estimates.Count;i++)
{
sys.EstimateNo = employee.EstimateNo;
sys.CustID = employee.CustID;
sys.ProductName = employee.estimates[i].ProductName;
sys.Quantity = employee.estimates[i].Quantity;
sys.Price = employee.estimates[i].Price;
sys.Amount = employee.estimates[i].Amount;
sys.Total=employee.total;
sys.Tax1=employee.tax1;
sys.Tax2 = employee.tax2;
sys.Tax3 = employee.tax3;
sys.Discount = employee.Discount;
sys.SubTotal = employee.subtot;
sys.GrandTotal = employee.grandtotal;
db.EstimateMasters.Add(sys);
db.SaveChanges();
}
This is my view code:
<div> #Html.LabelFor(m =>m.CustID)
#Html.DropDownList("CustID", "---Select---")
</div>
</div>
<div>
#Html.LabelFor(m => m.CustFname)
#Html.TextBoxFor(m =>m.CustFname)
#Html.LabelFor(m=>m.CompanyName)
#Html.TextBoxFor(m =>m.CompanyName)
</div>
I am getting this error on DropDownList: The ViewData item that has the key 'CustID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'. Can anyone help me?
You have to pass list to dropdown but here you are passing CustID and that is Integer. This is causing error.
Try following code:
1) Create a list with your items.
#{
List<SelectListItem> CustIDlistItems= new List<SelectListItem>();
CustIDlistItems.Add(new SelectListItem
{
Text = "text1",
Value = "value1"
});
CustIDlistItems.Add(new SelectListItem
{
Text = "text2",
Value = "value2",
Selected = true
});
CustIDlistItems.Add(new SelectListItem
{
Text = "text3",
Value = "value3"
});
}
2) Pass newly created list to view with list as a parameter.
#Html.DropDownListFor(model => model.Yourproperty, CustIDlistItems, "-- Select Status --")
Hope this will help you..!
EDIT :
You can utilize following example for creating dynamic list from database.
public IEnumerable<SelectListItem> GetTrainingSubjectsList(int selectedValue)
{
List<SelectListItem> TrainingSubjectsList = new List<SelectListItem>();
TrainingSubjectsList.Add(new SelectListItem() { Selected = true, Text = "Select Subject", Value = "" });
var TrainingSubjects = (from subjects in _context.TrainingDetails.Where(c => c.IsDeleted == false)
select subjects).ToList();
foreach (TrainingDetail TrainingDetail in TrainingSubjects)
{
SelectListItem Item = new SelectListItem();
Item.Text = TrainingDetail.Title;
Item.Value = TrainingDetail.TrainingDetailId.ToString();
if (selectedValue == TrainingDetail.TrainingDetailId)
{
Item.Selected = true;
}
TrainingSubjectsList.Add(Item);
}
return TrainingSubjectsList;
}