how to retrieve the other values in the business entity - asp.net

The method has a return type of collection<businessEntity>. I am calling the method from the aspx page in order to populate a drop down -> ddlDropDown. I am binding he DataTextField of the ddlDropDown with the BusinessEntity.Name and the DataValueField with BusinessEntity.Id, the business entity contains another id which is BusinessEntity.ProductId. I need to use the ProductId of the value selected in the drop down list in the code behind. Can you help suggest how I can do so?
One possible way could be to call the method in the page_Load on the code behind and save the collection in a hidden variable and when required do a loop through in the hidden variable and retrieve the selected value Product Id.
Your thoughts please.

You could certainly accomplish this using a hidden field.
Here's another idea: bind the DataValueField to a special derived string, containing the BusinessEntity.Id AND the BusinessEntity.ProductId.
In other words, concatenate the BusinessEntity.Id and BusinessEntity.ProductId into a single string, seperated by the pipe ("|") symbol for example.
E.g to bind:
ddlFoo.DataValueField = string.Format("{0}|{1}", "Id", "ProductId");
Then to retrieve selected item:
var id = ddlFoo.SelectedValue.Split("|")[0];
var productId = ddlFoo.SelectedValue.Split("|")[1];
Saves you looping/matching. Again, its not ideal, but then again neither is binding multiple values types to a dropdownlist.

Related

Array in gridview

I have a string array data[].I need to bind this string array as datasource in gridview.
I have values in data array.
I write the code
gridview_forecast.DataSource = data;
gridview_forecast.DataBind();
I got an error as "A data item was not found in the container. The container must either implement IDataItemContainer, or have a property named DataItem."
You cannot directly assign an array to GridView DataSource when GridView.AutoGenerateColumns is False. One way to do this convert your array to ArrayList or DataTable,
then assign it to GridView DataSource.
For an example click here

ContextTextType and TableName for LinqDataSource when data source is List<string>

I have a LinqDataSource defined like this:
<asp:LinqDataSource ID="LinqDataSource1" runat="server" OnSelecting="LinqDataSource_FileSelecting"></asp:LinqDataSource>
In LinqDataSource_FileSelecting, it returns/sets a List<string> to e.Result, where e is the EventArgs (LinqDataSourceSelectEventArgs) in the Selecting event of the LinqDataSource. I'm getting this error when the page loads:
"The ContextTypeName property of LinqDataSource 'LinqDataSource1' must specify a data context type."
Based on this message and looking at the docs, I need to set the ContextTypeName and TableName properties of the LinqDataSource. ContextTypeName would normally be the name of a class, and TableName would be the name of an enumerable property within that class.
When the data source is a List<string> I'm not sure what ContextTypeName or TableName I can assign. I've tried System.Collections.Generic.List<string> for the ContextTypeName, but that didn't work, I received "Could not load type 'System.Collections.Generic.List<string>'"
I realize the LinqDataSource may not be the appropriate control when the data source is a List<string> generated within the Selecting event. But is there a ContextTypeName and TableName I can set for this scenario?
Found the answer. Turns out that you can omit ContextTypeName and TableName when using the Selecting event and assigning a List<string> to e.Result. However, if you assign null to e.Result, then this error will occur since ASP.NET doesn't know the type of data. My code on the Selecting event was designed to set a non-null value to e.Result, but a separate problem was leading to null being set to e.Result ... leading to this error.

Binding Tuples to a GridView

private List<Tuple<int, string>> GetEmpDetails()
{
return (from r in dataContext.Emp
select new Tuple<int, string>(r.ID, r.Name)).ToList();
}
I am returing a list of Tuple from WCF Service & Binding to a gridview
But when i bind it to a GridView It shows header as Item1 & Item2. Is there any way I can change the Tuple Property Names
you can't it's a tuple, this is the meaning of tuple, some values attached.
And it wasn't created for this abuse you're doing with it, you shouldn't bind a tuple to ui.
create a presentation model and bind him.

Problem with getting selected OBJECT from dropdownlist

I have a problem with getting selected objectfrom my list.
I bind collection of users to dropdownlist by:
ddlContractors.DataSource = service.GetAllUsers();
ddlContractors.DataTextField = "Name";
ddlContractors.DataValueField = "Id";
ddlContractors.DataBind();
It's working.
But when I try getting selected object by:
var user = (User)ddlContractors.SelectedItem;
I get:
(User)ddlContractors.SelectedItem Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'GWDSite.GWDService.User'
How can I get object user from dropdownlist ? I can change type of my list control if it is necessary
The value field in the dropdown list is the field "Id" not the User object. so 'SelectedItem' is returning the "Id" value -- not the object. You can use that Id to lookup the User object (from session or cache or wherever you can keep it)
You cant.
The SelectedItem is of type ListItem and you cannot just typecast a listItem back into your custom class i.e user.
You can only get the text or the value associated with the item that was selected via SelectedItem / SelectedValue
What you need to do is use that text / value and maybe retrieve your corresponding "User" object based on that text / value from somewhere (depending on how you are doing your state management).
use SelectedValue instead of SelectedItem
WEB APPLICATION
As you are working with web app , approach i was describng will not work here.
you can get the ID of the selected item and use this ID as a parameter to retrive the object from the service layer but if the object is expensive to create than use caching to store your object and retrive it wheb needed.

Best way of implementing DropDownList in ASP.NET MVC 2?

I am trying to understand the best way of implementing a DropDownList in ASP.NET MVC 2 using the DropDownListFor helper. This is a multi-part question.
First, what is the best way to pass the list data to the view?
Pass the list in your model with a SelectList property that contains the data
Pass the list in via ViewData
How do I get a blank value in the DropDownList? Should I build it into the SelectList when I am creating it or is there some other means to tell the helper to auto create an empty value?
Lastly, if for some reason there is a server side error and I need to redisplay the screen with the DropDownList, do I need to fetch the list values again to pass into the view model? This data is not maintained between posts (at least not when I pass it via my view model) so I was going to just fetch it again (it's cached). Am I going about this correctly?
Your best bet is to create a SelectList in your Controller - use my extension method here:
http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc
Pop that into ViewData using the same key as your property name:
ViewData["statusid"]=MySelectList
Then just use Html.DropDownFor(x=>x.StatusID) and you're all set.
Answering in parts:
The best way IMHO is to pass the list in the ViewModel like this:
public SelectList Colors
{
get
{
// Getting a list of Colors from the database for example...
List<Color> colors = GetColors().ToList();
// Returning a SelectList to be used on the View side
return new SelectList(colors, "Value", "Name");
}
}
To get a blank or default option like ( -- Pick a color -- ), you can do this on the view side:
#Html.DropDownListFor(m => m.Color, Model.Colors, "-- Pick a color --")
You'll have to fetch/populate the list again if it's part of the ViewModel.
Take a look at the following blog post. It can give you some tips:
Drop-down Lists and ASP.NET MVC
You could do something like:
<%= Html.DropDownListFor((x => x.ListItems), Model.ListItems, "")%>
or
<%= Html.DropDownList("ListItems", Model.ListItems, "")%>
The last param 'optionLabel' makes a blank list item
In this case, you can see ListItems is a property of the model.
I have made the view strongly typed to the model also.
(You know this already!)
Pass the list in your model with a SelectList property that contains the data
Yes, add it when you build the SelectList. (If you build the list using LINQ, Union might come in handy.)
Yes do do, and yes you are.
I find it more intuitive to work with a sequence of SelectListItems (rather than a SelectList).
For example, this would create an IEnumerable<SelectListItem> from a sequence of customer objects that you can pass to the Html.DropDownListFor(...) helper. The 'Selected' property will optionally set the default item in the dropdown list.
var customers = ... // Get Customers
var items = customers.Select(c => new SelectListItem
{
Selected = (c.Id == selectedCustomerId),
Text = c.Email,
Value = c.Id.ToString()
});

Resources