I have 2 points for today
I. I have a controller in which i have a public static method for getting the details for a checkbox like
public static List<country> GetCountryLists()
{
List<country> countries = new List<country>();
country _country = new country() { countryname = "Select a country", value = "0" };
country _country1 = new country() { countryname = "India", value = "India" };
country _country2 = new country() { countryname = "USA", value = "USA" };
countries.Add(_country);
countries.Add(_country1);
countries.Add(_country2);
return countries;
}
Currently , i am using this function via
ViewData["country"] = GetCountryLists();
is it ok for me to use this same function like this one in the view, so that I do not need to use the viewdata object,
<%: Html.DropDownList("country", new SelectList(UserController.GetCountryLists(), "value", "countryname", "0"))%>
Kindly suggest me the best practice.
II. Also i have another query, when i use the same id & name for the radiobuttons, validation at the client side is working fine.
If I use the same condition for a group of checkboxes, i get do not get the checkboxes highlighted during client validation and only during server validation, i get the error message, but the controls [checkboxes] do not have a red border indicating the error.
I have used my own html helper to generate the checkboxlist as per http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
Kindly let me know if there is any possible solution for this problem too. As i am new to asp.net mvc2, i am not sure of using these.. kindly suggest me accordingly.
is it ok for me to use this same function like this one in the view, so that I do not need to use the viewdata object
No, this is not good practice and violation of the MVC pattern for various reasons. Views shouldn't pull information. They should only use the information that it is being passed in the view model. It is the controller's responsibility to invoke various methods to fetch data and then construct a view model containing all the necessary information needed for the view and then pass this view model to the view. So here's the suggested way:
<%= Html.DropDownListFor(
x => x.Country,
new SelectList(Model.Countries, "value", "countryname")
) %>
or with the ugly/weakly typed/avoid to use/requiring magic strings ViewData:
<%= Html.DropDownList(
"Country",
new SelectList((IEnumerable)ViewData["Countries"], "value", "countryname")
) %>
and it is the responsibility of the control to populate either the view model properties or the ugly ViewData.
As far as your second question is concerned you will need to show your code in order to see what is wrong with it. From your description what I can say is that you cannot have two elements with the same id in the DOM or you get invalid markup.
Related
i am new to .net..i have to develop an asp.net application.
The UI of the web page will have a Data-bound Grid control on the Home page and there will be a Textbox where users can enter their search criteria.
I know to do this by using ado.net concept...
But i am supposed to do it using generics concept.How can i store the values in the generic list or dictionary of .net and filter the data based on the text entered in the text box.
Please help me out..
Thanks in advance..
You can indeed bind a GridView to List<T>, I do it all the time, like this:
Create a POCO for the data
public class SomeData
{
public string SomeField {get;set;}
public string SomeOtherField {get;set;}
}
Build the list (either manually or as a result a DB query) e.g.
var mylist = new List<SomeData>();
var myitem = new SomeData()
{
SomeField = "Hello",
SomeOtherField = "World"
};
To Filter the data do something like this:
myfilter = MyTextBox.Value;
mylist = mylist.Where(somedata => somedata.SomeField.Equals(myfiltervalue)).ToList();
Bind it to the GridView
mygridview.DataSource = mylist;
mygridview.DataBind();
And this is it!!
I assume you know ado.net and how to bind gridview.
You just need to iterate through your database resultset and add it to list and bind it.
Following link might help you to begin with:
http://www.aspsnippets.com/Articles/How-to-bind-GridView-with-Generic-List-in-ASPNet-using-C-and-VBNet.aspx
Pass your textbox value to your database query/stored procedure as parameter and return the result based on search value.
Edit:
You may want to use FindAll, Find method.
Check below link:
http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx
how can i get a form field id after submitting the form. im trying like this:
ViewData.TemplateInfo.GetFullHtmlFieldId(logOnParts.Part.UserNameOrEmail)
but no work on controller side. i need to get "Part_UserNameOrEmail" something..
if (String.IsNullOrEmpty(logOnParts.Part.UserNameOrEmail))
{
ModelState.AddModelError("Part_UserNameOrEmail", "error");
TempData["logon-focus-field"] = "Part_UserNameOrEmail";
}
so i will focus the field on view side like this:
$(document).ready(function () {
$('#TempData["logon-focus-field"]').focus();
});
A controller should absolutely not need such information. The generated id is a view specific information. If you need this in a controller this simply means that you have some serious design problem with your application. Unfortunately as you haven't explained your scenario in the question it is difficult to help you solving this problem. So in your controller you could do this:
Expression<Func<MyViewModel, string>> expression = x => x.Part.UserNameOrEmail;
string name = ExpressionHelper.GetExpressionText(expression);
string id = new TemplateInfo().GetFullHtmlFieldId(name);
Say for example if I have a business entity -> Customer, which has customerId, customerName and customerType. I have created an asp:Hidden Variable hdnCustomer to runat="server"
If I wanted to serialize the value of the customer business entity (in the code behind) to the hdnCustomer then how would I do that? Also once serialized how would I deserialize it?
// Pseudo code
Collection<Customer> customerList = new Collection<Customer>();
customerList = BusinessAccess.GetCustomerList();
hdnCustomer = serialize and assign the value of 'customerList' to hdnCustomer;
...
...
// Later on a select index change of one of the drop down lists
Inside the event handler for the drop down list:
{
Collection<Customer> customerList = new Collection<Customer>();
customerList = deserialize the value from hdnCustomer
int a = Convert.ToInt32(ddlDropDown.SelectedValue);
foreach(a in customerList)
{
// Do something
}
}
You can serialise to and from XML using XmlSerializer:
http://support.microsoft.com/kb/815813
However, if you just store the object in the ViewState[] collection that should work better:
ViewState["Customer"] = customerList;
It does the same thing: store the serialisable object in the page, hidden from the user: but it won't be in a human-readable format.
(edit: To deserialise, just get the value of ViewState["Customer"], checking for a null before using it!)
edit 2: a useful link about storing objects in ViewState:
http://www.beansoftware.com/ASP.NET-Tutorials/ViewState-In-ASP.NET.aspx
Hope that helps.
I think .net has already providing some classes to do so, look at this example
My problem is that I am trying to return a simple query that contains an object Story. The Story object has a UserId in the table which links to aspnet_users' UserId column. I have created a partial class for Story that adds the UserName property since it does not exist in the table itself.
The following query gets all stories; however, a pagination helper takes the query and returns only what's necessary once this is passed back to the controller.
public IQueryable<Story> FindAllStories(){
var stories = (from s in db.Stories
orderby s.DateEntered descending
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
}
);
return stories;
}
When the helper does a .count() on the source it bombs with the following exception:
"Explicit construction of entity type 'MyWebsite.Models.Story' in query is not allowed."
Any ideas? It's not a problem with the helper because I had this working when I simply had the UserName inside the Story table. And on a side note - any book recommendations for getting up to speed on LINQ to SQL? It's really kicking my butt. Thanks.
The problem is precisely what it tells you: you're not allowed to use new Story as the result of your query. Use an anonymous type instead (by omitting Story after new). If you still want Story, you can remap it later in LINQ to Objects:
var stories = from s in db.Stories
orderby s.DateEntered descending
select new
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
};
stories = from s in stories.AsEnumerable() // L2O
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
...
};
If you really need to return an IQueryable from your method and still need the Username of the user you can use DataContext.LoadOptions to eagerload your aspnet_user objects.
See this example.
Trying to create a select list with a first option text set to an empty string. As a data source I have a List of a GenericKeyValue class with properties "Key" & "Value". My current code is as follows.
<%= this.Select(x => x.State).Options(ViewData[Constants.StateCountry.STATES] as IList<GenericKeyValue>, "Value", "Key").Selected(Model.State) %>
This gets fills the select list with states, however I am unsure at this point of an elegant way to get a first option text of empty string.
"Trying to create a select list with a first option text set to an empty string." The standard way isn't fluent but feels like less work:
ViewData[Constants.StateCountry.STATES] = SelectList(myList, "Key", "Value");
in the controller and in the view:
<%= Html.DropDownList(Constants.StateCountry.STATES, "")%>
Sure you can, but you add it to your list that you bind to the dropdown...
List<State> list = _coreSqlRep.GetStateCollection().OrderBy(x => x.StateName).ToList();
list.Insert(0, new State { Code = "Select", Id = 0 });
ViewData["States"] = new SelectList(list, "Id", "StateName", index);
Or this...
Your view;
<%=Html.DropDownList("selectedState", Model.States)%>
Your controller;
public class MyFormViewModel
{
public SelectList States;
}
public ActionResult Index()
{
MyFormViewModel fvm = new MyFormViewModel();
fvm.States = new SelectList(Enumerations.EnumToList<Enumerations.AustralianStates>(), "Value", "Key", "vic");
return(fvm);
}
Without extending anything - you can't.
Here's what author says:
One final point. The goal of MvcFluentHtml was to leave the opinions to you. We did this by allowing you to define your own behaviors. However, it is not without opinions regarding practices. For example the Select object does not have any “first option” functionality. That’s because in my opinion adding options to selects is not a view concern.
Edit:
On the other hand - there is 'FirstOption' method for Select in newest source code.
Download MvcContrib via svn, build and use.