asp.net mvc3, why my dropdownlist is not selected? - asp.net-mvc-3

I create my selectlist from enum.
[Flags]
public enum Age
{
New_Born = 1,
Toddler = 2,
Preschool = 4,
Kindergarten = 8,
Elementary_School = 16,
Middle_School = 32,
High_School = 64
}
var age = from Age e in Enum.GetValues(typeof(Age))
select new { Id = (int)e, Name = e.ToString().Replace("_", " ") };
I tried both:
var ageList = new SelectList(age, "Id", "Name", (int)Model.Child.Age);
or
var ageList = new SelectList(age, "Id", "Name", Model.Child.Age);
#Html.DropDownListFor(m => m.Child.Age, ageList, "Your Child's Age")
Everything works except the selected value didn't get selected.
EDIT: after hours testing, finally fix it.
chagne Id = (int)e to Id = e.
var age = from Age e in Enum.GetValues(typeof(Age))
select new { Id = e, Name = e.ToString().Replace("_", " ") };
var ageList = new SelectList(age, "Id", "Name", Model.Child.Age);

I just created a similar example and worked out your problem and I believe you have two problems with your code:
In your controller code, you should have your first option, like this:
SelectList selectList = new SelectList(items, "Id", "Name", (int)Qualities.Whatever);
And in your view:
<%= this.Html.DropDownListFor(m => m.List.SelectedValue, this.Model.List, "Qualities") %>
Think about it, why would you pass the SelectList twice? You should pass the selected value and then the list of values.
The fact that I didn't use Razor view engine is irrelevant.

after hours testing, finally fix it. chagne Id = (int)e to Id = e.
var age = from Age e in Enum.GetValues(typeof(Age))
select new { Id = e, Name = e.ToString().Replace("_", " ") };
var ageList = new SelectList(age, "Id", "Name", Model.Child.Age);

Related

Bulk updates using linq entities

I have a list of object like
List
category has properties, CategoryId, CategoryName, Categorymessage,
I have to use this list to update records in the database table
Categories, which has the same columns CategoryId, CategoryName, CategoryMessage
for the items in list which have a matching CategoryId as in the database table
How can I do that as a bulk update, using Entity framework extensions,
the examples I saw have the update value hard coded like below, (statusId =2),
whereas for me that value has to be retrieved from the item in the list which matches the categoryId in the database table.
context.Tasks.Update(
t => t.StatusId == 1,
t => new Task {StatusId = 2});
Thanks in advance.
I am not sure whether this what you are looking for? I haven't run this code.
List<Category> categoryList = new List<Category> {
new Category { Id = 1, Message = "A", Name = "A"},
new Category { Id = 2, Message = "B", Name = "B"},
new Category { Id = 3, Message = "C", Name = "C"},
new Category { Id = 4, Message = "D", Name = "D"},
};
using (var container = new Model1Container())
{
IQueryable<Category> categoryQueryable = container.Categories.Where(x => categoryList.Any(t => t.Id == x.Id));
foreach (Category item in categoryQueryable)
{
var categorySource = categoryList.Where(x => x.Id == item.Id).Select(m => m).FirstOrDefault();
item.Message = categorySource.Message;
item.Name = categorySource.Message;
}
container.SaveChanges();
}

Why does my selected value not get added to my SelectListItem as the “Text” and “Value” properties do?

I am trying to set a default value of a list in a partial view. The partial view is called using this…
#Html.Action("Acton", "Controller", new { department = item.Data.departmentNumber, defaultValue="someValue" })
Then in the controller I have…
[ChildActionOnly]
public ActionResult Categories(int? id, int? department, string defaultValue)
{
var typeList = from e in db.Rubrics where e.DepartmentID == department select e;
var selectedRubrics = typeList.Select(r => r.Category);
List<String> rubricsList = selectedRubrics.ToList();
var categories = new List<SelectListItem>();
for (int i = 0; i < rubricsList.Count(); i++)
{
categories.Add(new SelectListItem
{
Text = rubricsList[i],
Value = rubricsList[i],
Selected = (defaultValue == "defaultValueGetsSentToView")
});
}
var ViewModel = new RubricsViewModel
{
Category = "Select a Category",
Categories = categories
};
return View(ViewModel);
}
Why does my selected value not get added to my SelectListItem as the “Text” and “Value” properties are? Thanks for any help!
Assuming the values in the code are the literal values you are using, "defaultValue" is "someValue" and you are setting selected with the comparison defalutValue == "defaultValueGetsSentToView".
"someValue" == "defaultValueGetsSentToView" evaluates to false.

How to iterate through GroupBy groups using Dynamic LINQ? [duplicate]

I am using Dynamic Linq helper for grouping data. My code is as follows :
Employee[] empList = new Employee[6];
empList[0] = new Employee() { Name = "CA", State = "A", Department = "xyz" };
empList[1] = new Employee() { Name = "ZP", State = "B", Department = "xyz" };
empList[2] = new Employee() { Name = "AC", State = "B", Department = "xyz" };
empList[3] = new Employee() { Name = "AA", State = "A", Department = "xyz" };
empList[4] = new Employee() { Name = "A2", State = "A", Department = "pqr" };
empList[5] = new Employee() { Name = "BA", State = "B", Department = "pqr" };
var empqueryable = empList.AsQueryable();
var dynamiclinqquery = DynamicQueryable.GroupBy(empqueryable, "new (State, Department)", "it");
How can I get back the Key and corresponding list of grouped items i.e IEnumerable of {Key, List} from dynamiclinqquery ?
I solved the problem by defining a selector that projects the Key as well as Employees List.
var eq = empqueryable.GroupBy("new (State, Department)", "it").Select("new(it.Key as Key, it as Employees)");
var keyEmplist = (from dynamic dat in eq select dat).ToList();
foreach (var group in keyEmplist)
{
var key = group.Key;
var elist = group.Employees;
foreach (var emp in elist)
{
}
}
The GroupBy method should still return something that implements IEnumerable<IGrouping<TKey, TElement>>.
While you might not be able to actually cast it (I'm assuming it's dynamic), you can certainly still make calls on it, like so:
foreach (var group in dynamiclinqquery)
{
// Print out the key.
Console.WriteLine("Key: {0}", group.Key);
// Write the items.
foreach (var item in group)
{
Console.WriteLine("Item: {0}", item);
}
}

Get list on basis of dropdownlist data in asp.net mvc3

I have two dropdownlists in my module.
In one dropdownlist, I have hardcoded all the operators like <,>,<=,>=,==
In second dropdownlist, I have hardcoded salary of employees like 1000,2000,3000,4000....50000
Now if I select < from one list and 2000 from second list and click on submit button I should get list of employees who have salary less than 2000.
I want to do this in asp.net mvc3
How can I accomplish this task? Do I need to write a stored procedure for this?
I have created dropdownlist like:
viewModel.OperatorsList = new[]
{
new SelectListItem { Value = "<", Text = "<" },
new SelectListItem { Value = ">", Text = ">" },
new SelectListItem { Value = "<=", Text = "<=" },
new SelectListItem { Value = ">=", Text = ">=" },
new SelectListItem { Value = "==", Text = "==" }
};
viewModel.SalaryList = new[]
{
new SelectListItem { Value = "1000", Text = "1000" },
new SelectListItem { Value = "2000", Text = "2000" },
new SelectListItem { Value = "3000", Text = "3000" },
// and so on
};
and I have used this to show dropdownlist in view:
<%: Html.DropDownListFor(x => x.Operators, Model.OperatorsList)%>
well, you could do something like that
assuming viewModel is... your viewModel, and you've got an entity Employee with a property Salary (int in this sample, it's probably a decimal in real world)
create a static helper class
public static class MyHelper
{
// a dictionary for your operators and corresponding ExpressionType
public static Dictionary<string, ExpressionType> ExpressionTypeDictionary = new Dictionary<string, ExpressionType>
{
{"<", ExpressionType.LessThan},
{">", ExpressionType.GreaterThan},
{">=", ExpressionType.GreaterThanOrEqual}
//etc
};
//a method to filter your queryable
public static IQueryable<Employee> FilterSalary(this IQueryable<Employee> queryable, int salary, string operatorType)
{
//left part of the expression : m
var parameter = Expression.Parameter(typeof(Employee), "m");
//body is the right part of the expression : m
Expression body = parameter;
//m.Salary
body = Expression.Property(body, "Salary");
//m.Salary <= 1000 (for example)
body = Expression.MakeBinary(ExpressionTypeDictionary[operatorType], body, Expression.Constant(salary));
//m => m.Salary <=1000
var lambda = Expression.Lambda<Func<Employee, bool>>(body, new[] { parameter });
//so it will be queryable.Where(m => m.Salary <= 1000)
return queryable.Where(lambda);
}
}
usage
var queryable = context.All<Employee>();//or something like that, returning an IQueryable<Employee>
queryable = queryable.FilterSalary(viewModel.Salary, viewModel.Operators);

Referencing the collection your working on within LINQ

I am working with linq, and im wondering if there is any way that I might reference the collection I am working on from within my linq code? What I am looking for is something like this:
let result = (from t in someCollection
where t == something
select t).Where(res => res.start == THIS.Min(temp => temp.start))
So what I want to achieve in this query is that the THIS variable should provide a reference to the collection that the where clause is being applied to:
(from t in someCollection
where t == something
select t)
There are lots of ways to get around this problem, but I am specifically interested in a way of using a reference to the collection in use. Hope some of you know something about this!
Thanks!
The way to do what your example states is like this:
var minValue = someCollection.Min(x => x.start);
var result = from t in someCollection
where t.id > 5 // replace this line with your "where t == something"
where t.start == minValue
select t;
but say that you have to do some kind of other comparison for every
element in your collection to every other element. Is some there some
way of doing a thing like this?
If you really need to compare one item with every other item in the list, you could pattern your code like this:
var result = from t in someCollection
where t.id > 5 // replace this line with your "where t == something"
let minValue = someCollection.Min (x => x.start)
where t.start == minValue
select t;
The problem with the second example is that every item you visit in your someCollection it will be forced to recalculate the minValue.
Now, here's a completely contrived example that illustrates having to access the entire collection while accessing each member of the collection. It simply goes through a list of items and outputs each item along with all the other items that have lesser dates:
var eventItems = new[]
{
new { Name = "alpha", DateCreated = DateTime.Today.AddDays(1) },
new { Name = "bravo", DateCreated = DateTime.Today.AddDays(2) },
new { Name = "charlie", DateCreated = DateTime.Today.AddDays(-1) },
new { Name = "delta", DateCreated = DateTime.Today.AddDays(-5) },
new { Name = "echo", DateCreated = DateTime.Today.AddDays(-3) },
new { Name = "foxtrot", DateCreated = DateTime.Today.AddDays(3) },
new { Name = "golf", DateCreated = DateTime.Today.AddDays(-4) }
};
var results = from item in eventItems
where item.Name.Length > 2
let prevDays = eventItems.Where (i => i.DateCreated < item.DateCreated)
select new
{
Name = item.Name,
CurrentDate = item.DateCreated,
PreviousItems = prevDays
};
The output:
Perhaps one of these examples will help you with your exact problem.

Resources