Model.cs contains the Data of the User which is stored in a list type Now We have to fetch all those students whose age is more than 25.
public class Model
{
public int Age { get; set; }
public string Name { get; set; }
public string Sports { get; set; }
List<Model> objModels = new List<Model>() {
new Model { Name = "Manish", Age = 27, Sports = "Cricket" },
new Model { Name = "Rajan", Age = 25, Sports = "FootBall" },
new Model { Name = "Prashant", Age = 25, Sports = "Kabaddi" },
new Model { Name = "Garima", Age = 24, Sports = "Ludo" },
new Model { Name = "Neha", Age = 25, Sports = "Carom" }
};
}
ModelController.cs
public class ModelController : Controller
{
// GET: Model
public ActionResult Index()
{
List<Model> objModel = new List<Model>();
var query = from models in objModel select models;
foreach(var item in query.ToList())
{
objModel.Add(
new Model
{
Name = item.Name.ToString(),
Age = int.Parse(item.Age.ToString()),
Sports = item.Sports.ToString()
});
}
return View(objModel);
}
}
But The object is always empty because it is not fetching the data from the model class.
Hi have you tried to do:
public class Model
{
public int Age { get; set; }
public string Name { get; set; }
public string Sports { get; set; }
public List<Model> Models
{
get
{
return objModels;
}
set {
Model = value;
}
}
List<Model> objModels = new List<Model>() {
new Model { Name = "Manish", Age = 27, Sports = "Cricket" },
new Model { Name = "Rajan", Age = 25, Sports = "FootBall" },
new Model { Name = "Prashant", Age = 25, Sports = "Kabaddi" },
new Model { Name = "Garima", Age = 24, Sports = "Ludo" },
new Model { Name = "Neha", Age = 25, Sports = "Carom" }
};
}
And then use it in your controller as :
List<Model> newModelList=new List<Model>();
Model objModel = Model;
var query = from models in objModel.Models where models.age<25 select models;
foreach (var item in query.ToList())
{
newModelList.Add(
new Model
{
Name = item.Name.ToString(),
Age = int.Parse(item.Age.ToString()),
Sports = item.Sports.ToString()
});
}
return View(newModelList);
DBCOntext.cs - a new class for Handeling The Data.
public class DBContext
{
List<Model> objModel = new List<Model>();
public List<Model> GetData()
{
objModel.Add(new Model
{
Name = "Manish",Age = 27,Sports = "Cricket"
});
objModel.Add(new Model
{
Name = "Rajan",Age = 25,Sports = "FootBall"
});
objModel.Add(new Model
{
Name = "Prashant", Age = 25,Sports = "Kabaddi"
});
objModel.Add(new Model
{
Name = "Garima", Age = 24,Sports = "Ludo"
});
objModel.Add(new Model
{
Name = "Neha",Age = 25,Sports = "Carom"
});
return objModel;
}
}
And Controller class to access all the DBContext Data which can be used to send the data to the View
List<Model> objModel = new List<Model>();
// GET: Model
public ActionResult Index()
{
DBContext db = new DBContext();
var query = from models in db.GetData() where models.Age>25 orderby models.Age select models;
foreach (var item in query.ToList())
{
objModel.Add(
new Model
{
Name = item.Name.ToString(),
Age = int.Parse(item.Age.ToString()),
Sports = item.Sports.ToString()
});
}
return View(objModel);
}
Related
I am having problem adding to the model. I want to have a list in the Root1 or in the Viewmodel like fullname and authors list.
newModel1
AuthorsAccepted count=4
FullName = Jack
AuthorsAccepted count=4
FullName = Time Dean
With the code below it only adds the last one to the Root1. I created a a third model. Is there a way I can add to the third model both the lists or in Root1.
var fullName = "Jack";
var fullName2 = "Tim Dean";
var authors1 = new List<AuthorsAccepted1>() {
new AuthorsAccepted1(){ id = 1, Name="Bill"},
new AuthorsAccepted1(){ id = 2, Name="Steve"},
new AuthorsAccepted1(){ id = 3, Name="jon"},
new AuthorsAccepted1(){ id = 4, Name="nick"}
};
var authors2 = new List<AuthorsAccepted1>() {
new AuthorsAccepted1(){ id = 1, Name="jack"},
new AuthorsAccepted1(){ id = 2, Name="tim"},
new AuthorsAccepted1(){ id = 3, Name="james"},
new AuthorsAccepted1(){ id = 4, Name="mary"}
};
var newModel1 = new Root1();
newModel1.FullName = fullName;
newModel1.AuthorsAccepted = authors1;
var newModel2 = new Root1();
newModel2.FullName = fullName2;
newModel2.AuthorsAccepted = authors2;
}
}
public class Root1
{
public string FullName { get; set; }
public List<AuthorsAccepted1> AuthorsAccepted { get; set; }
}
public class AuthorsAccepted1
{
public string Name { get; set; }
public int id { get; set; }
}
public class Viewmodel
{
public Root1 AllModel { get; set; }
}
I have the next mongo document structure :
_id
-countryCode
-keywordID
-name
-displayName
-categories:[Array]
-_id
-name
-position
-canonical
I would like to get all the keywords that are in a specific category only knowing the category's ID. I am using the mongo C# driver but don't know how could I check what's inside that array.
I would like to send a list with the category ID's and get back all the keywords that have a category from that list.
public async Task<List<Keyword>> GetKeywords(List<long> keywordCatIds, string countryCode)
{
var mongoCollection = MongoDatabase.GetCollection<Keyword>("Keywords");
try
{
FilterDefinition<Keyword> mongoFilter = Builders<Keyword>.Filter.In(c=>c.Categories, keywordCatIds);
return await mongoCollection.Find(mongoFilter,null).ToListAsync<Keyword>();
}
catch (Exception ex)
{
Logger.Error(ex, "Multiple ids for Country Code: {0}, ids: {1}", countryCode, string.Join(',', keywordCatIds.Select(s => s)));
return null;
}
}
Your In function looks like a "categories._id" filter in normal mongoDB. Which transitions into an ElemMatch. I created a project which fills the db, than selects
all the keywords that are in a specific category only knowing the category's ID
public class CustomID
{
public string CountryCode { get; set; }
public long KeywordId { get; set; }
public string Name { get; set; }
}
public class Keyword
{
[BsonId]
public CustomID Id { get; set; }
public List<Category> Categories { get; set; }
}
public class Category
{
[BsonId]
public long Id { get; set; }
public string Name { get; set; }
public int Position { get; set; }
}
internal class Program
{
public static IMongoDatabase MongoDatabase { get; private set; }
public static async Task Main()
{
var conventionPack = new ConventionPack
{
new CamelCaseElementNameConvention()
};
ConventionRegistry.Register(
"CustomConventionPack",
conventionPack,
t => true);
var client = new MongoClient();
MongoDatabase = client.GetDatabase("SO");
var ret = await GetKeywords(new List<long> {1L, 2L}, "HU-hu");
// ret is A and B. C is filtered out because no category id of 1L or 2L, D is not HU-hu
}
public static async Task<List<Keyword>> GetKeywords(List<long> keywordCatIds, string countryCode)
{
var mongoCollection = MongoDatabase.GetCollection<Keyword>("keywords");
// be ware! removes all elements. For debug purposes uncomment>
//await mongoCollection.DeleteManyAsync(FilterDefinition<Keyword>.Empty);
await mongoCollection.InsertManyAsync(new[]
{
new Keyword
{
Categories = new List<Category>
{
new Category {Id = 1L, Name = "CatA", Position = 1},
new Category {Id = 3L, Name = "CatC", Position = 3}
},
Id = new CustomID
{
CountryCode = "HU-hu",
KeywordId = 1,
Name = "A"
}
},
new Keyword
{
Categories = new List<Category>
{
new Category {Id = 2L, Name = "CatB", Position = 2}
},
Id = new CustomID
{
CountryCode = "HU-hu",
KeywordId = 2,
Name = "B"
}
},
new Keyword
{
Categories = new List<Category>
{
new Category {Id = 3L, Name = "CatB", Position = 2}
},
Id = new CustomID
{
CountryCode = "HU-hu",
KeywordId = 3,
Name = "C"
}
},
new Keyword
{
Categories = new List<Category>
{
new Category {Id = 1L, Name = "CatA", Position = 1}
},
Id = new CustomID
{
CountryCode = "EN-en",
KeywordId = 1,
Name = "EN-A"
}
}
});
var keywordFilter = Builders<Keyword>.Filter;
var categoryFilter = Builders<Category>.Filter;
var mongoFilter =
keywordFilter.ElemMatch(k => k.Categories, categoryFilter.In(c => c.Id, keywordCatIds)) &
keywordFilter.Eq(k => k.Id.CountryCode, countryCode);
return await mongoCollection.Find(mongoFilter).ToListAsync();
}
}
I want to split my list by value, but I don't need group the result,
this is my list :
var source = new List<Car>() {
new Car() { ID = 1, Model = "Model A" },
new Car() { ID = 2, Model = "Model B" },
new Car() { ID = 3, Model = "Model B" },
new Car() { ID = 4, Model = "Model B" },
new Car() { ID = 5, Model = "Model A" },
new Car() { ID = 6, Model = "Model A" }
};
var result = GetListOfAdjacentCarsOfSameModel();
I want the resulting list to look like this:
- Model A
- ID = 1, Model = "Model A"
- Model B
- ID = 2, Model = "Model B"
- ID = 3, Model = "Model B"
- ID = 4, Model = "Model B"
- Model A
- ID = 5, Model = "Model A"
- ID = 6, Model = "Model A"
I suggest a simple loop:
var result = new List<List<Car>>();
foreach (var item in source)
if (result.Count <= 0 || result[result.Count - 1][0].Model != item.Model)
result.Add(new List<Car>() {item}); // Create a new group, add item to it
else
result[result.Count - 1].Add(item); // Add item into the last group
public class Car
{
public int ID { get; set; }
public string Model { get; set; }
}
public class Result
{
public string Model { get; set; }
public int Count { get; set; }
}
var source = new List<Car>();
source.Add(new Car { ID = 1, Model = "Model A" });
source.Add(new Car { ID = 1, Model = "Model B" });
source.Add(new Car { ID = 1, Model = "Model B" });
source.Add(new Car { ID = 1, Model = "Model B" });
source.Add(new Car { ID = 1, Model = "Model A" });
source.Add(new Car { ID = 1, Model = "Model A" });
var result = new List<Result>();
if (source.Any())
{
string model = source[0].Model;
int count = 0;
foreach (var car in source)
{
if (car.Model == model)
{
count++;
}
else
{
result.Add(new Result { Model = model, Count = count });
model = car.Model;
count = 1;
}
}
result.Add(new Result { Model = model, Count = count });
}
foreach (var r in result)
{
Console.WriteLine(r.Model + " - " + r.Count);
}
I'm struggling with finding a simple way to do this, but you can always do it iteratively:
var source = new List<string>() {
"Model A",
"Model B",
"Model B",
"Model B",
"Model A",
"Model A"
};
string lastModel = null;
List<string> currentList = new List<string>();
var result = new List<List<string>>();
foreach (var model in source)
{
if (lastModel != null && model != lastModel)
{
result.Add(currentList);
currentList = new List<string>();
}
currentList.Add(model);
lastModel = model;
}
if (currentList.Any()) {
result.Add(currentList);
}
Now, it's easy to wrap that code in an extension method you can use on your car class:
var source = new List<Car>() {
new Car { Model = "Model A" },
new Car { Model = "Model B" },
new Car { Model = "Model B" },
new Car { Model = "Model B" },
new Car { Model = "Model A" },
new Car { Model = "Model A" }
};
var result = source.CollectAdjacentWithSameModel();
// elsewhere
public static class EnumerableExtensions
{
public static IEnumerable<IEnumerable<Car>> CollectAdjacentWithSameModel(this IEnumerable<Car> source)
{
var lastModel = default(Car);
List<Car> currentList = new List<Car>();
var result = new List<List<Car>>();
foreach (var model in source)
{
if (lastModel != null && model.Model != lastModel.Model)
{
result.Add(currentList);
currentList = new List<Car>();
}
currentList.Add(model);
lastModel = model;
}
if (currentList.Any())
{
result.Add(currentList);
}
return result;
}
}
public class Car {
public string Model { get; set; }
}
I have a dropdown (customer) and list of checkboxes (sales orders), dependent upon the currently selected customer. I would expect the checkboxes to clear if I select a new customer, but they are maintained from one to the other, despite the model being cleared in the postback.
I'm not a seasoned MVC developer, but I'm not sure why this should be. When debugging the ViewModel I'm sending back to the view, it is showing IsSelected = false for all the checkboxes, yet in the View, they are selected. What am I doing wrong? (Thanks in advance)
View Model:
namespace MvcTest1.Models
{
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
}
public class SalesOrder
{
public int SalesOrderID { get; set; }
public string Reference { get; set; }
public bool IsSelected { get; set; }
}
public class SalesOrderPageViewModel
{
public List<Customer> Customers { get; set; }
public int SelectedCustomerID { get; set; }
public List<SalesOrder> SalesOrders { get; set; }
}
}
Controller:
namespace MvcTest1.Controllers
{
public class SalesOrderPageController : Controller
{
[HttpGet]
public ActionResult Index()
{
SalesOrderPageViewModel viewModel = BuildViewModel(1);
return View(viewModel);
}
[HttpPost]
public ActionResult Index(SalesOrderPageViewModel viewModelInput)
{
SalesOrderPageViewModel viewModel = BuildViewModel(viewModelInput.SelectedCustomerID);
return View(viewModel);
}
public SalesOrderPageViewModel BuildViewModel(int customerID)
{
SalesOrderPageViewModel viewModel = new SalesOrderPageViewModel
{
Customers = new List<Customer>
{
new Customer { CustomerID = 1, Name = "Alan" },
new Customer { CustomerID = 2, Name = "Bob" },
new Customer { CustomerID = 3, Name = "Charlie" }
}
};
viewModel.SelectedCustomerID = customerID;
if (customerID == 1)
{
viewModel.SalesOrders = new List<SalesOrder>
{
new SalesOrder { SalesOrderID = 11, Reference = "AA11" },
new SalesOrder { SalesOrderID = 12, Reference = "AA22" },
new SalesOrder { SalesOrderID = 13, Reference = "AA33" }
};
}
if (customerID == 2)
{
viewModel.SalesOrders = new List<SalesOrder>
{
new SalesOrder { SalesOrderID = 21, Reference = "BB11" },
new SalesOrder { SalesOrderID = 22, Reference = "BB22" },
new SalesOrder { SalesOrderID = 23, Reference = "BB33" }
};
}
if (customerID == 3)
{
viewModel.SalesOrders = new List<SalesOrder>
{
new SalesOrder { SalesOrderID = 31, Reference = "CC11" },
new SalesOrder { SalesOrderID = 32, Reference = "CC22" },
new SalesOrder { SalesOrderID = 33, Reference = "CC33" }
};
}
return viewModel;
}
}
}
View:
#model MvcTest1.Models.SalesOrderPageViewModel
#{
ViewBag.Title = "SalesOrderPage";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>SalesOrderPage</h2>
<br /><br />
#using (Html.BeginForm())
{
#Html.DropDownListFor(model =>
model.SelectedCustomerID,
new SelectList(
Model.Customers,
"CustomerID",
"Name",
Model.SelectedCustomerID
),
new { id = "customerSelect" }
);
<script type="text/javascript">
$(function () {
$('#customerSelect').change(function () {
this.form.submit();
});
})
</script>
<br /><br />
for (int i = 0; i < Model.SalesOrders.Count(); i++)
{
#Html.DisplayFor(m => Model.SalesOrders[i].Reference)
#Html.CheckBoxFor(m =>
m.SalesOrders[i].IsSelected
)
<br />
}
}
Looks like Ryan is correct about ModelState.Clear(). Here's an article explaining why it is necessary:
http://patrickdesjardins.com/blog/modelstate-clear-is-required-to-display-back-your-model-object
I have an entity called ActionResult that my methods along the application returns. Now i want to map a returned object in the ActionResult to it's right place in an array of that object...
public class Core
{
public Employee[] Employees = new[] {
new Employee {
Name = "Jack",
Age = 21,
Salary = 1000
},
new Employee {
Name = "Carl",
Age = 35,
Salary = 1000
},
new Employee {
Name = "Tom",
Age = 41,
Salary = 1000
},
};
}
public class ActionResult
{
public string ActionID { get; set; }
public Employee Employee { get; set; }
}
public class Employee
{
public String Name { get; set; }
public int? Age { get; set; }
public int? Salary { get; set; }
public int? Level { get; set; }
}
public ActionResult MethodThatReturnsActionResultWithAnEmployee()
{
return new ActionResult {
ActionID = new Guid().ToString(),
Employee = new Employee {
Name = "Carl",
Age = 35,
Salary = 7000,
Level = 1
}
};
}
Now as you can see what i want to do is taking the Employee that is returned from the Method, and search in the array of Employees in the Core and update it using the new given data using AutoMapper.
AutoMapper will not search employee in some array for you. How it would know which employees should be considered as equal? You should search for employee manually, and use appropriate mapping method to update existing instance of employee with data from other employee instance:
Mapper.CreateMap<Employee, Employee>();
var result = MethodThatReturnsActionResultWithAnEmployee();
var employee = result.Employee;
var core = new Core();
var employeeToUpdate =
core.Employees.FirstOrDefault(e => e.Name == employee.Name);
Mapper.Map(employee, employeeToUpdate);
If you really want mapping to look like
Mapper.Map(result, core);
Then you should write your own type mapper for this:
public class ActionResultToCoreConverter : ITypeConverter<ActionResult, Core>
{
public Core Convert(ResolutionContext context)
{
var result = (ActionResult)context.SourceValue;
var employee = result.Employee;
var core = (Core)context.DestinationValue ?? new Core();
var employeeToUpdate =
core.Employees.FirstOrDefault(e => e.Name == employee.Name);
Mapper.Map(employee, employeeToUpdate);
return core;
}
}
And mapping will look like:
Mapper.CreateMap<Employee, Employee>(); // this map also required
Mapper.CreateMap<ActionResult, Core>()
.ConvertUsing<ActionResultToCoreConverter>();
var result = MethodThatReturnsActionResultWithAnEmployee();
var core = new Core();
Mapper.Map(result, core);
// if you want to create new Core instanse:
var core2 = Mapper<Core>(result);