creating list of custom object in mvc2 controller - asp.net-mvc-2

Model::::
public class Model1
{
public string Name { get; set; }
public string ProductName { get; set; }
}
ViewModel::::
public class ViewModel1
{
public List<Model1> model1;
}
controller:::::::::
var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
var nmodel = new Model1();
nmodel.Name = gf.Name;
nmodel.ProductName = doSomething(gf.ProductName);
// **Here I'm stuck====how do I add nmodel to newViewModel**
//**newViewModel.Add===does not work**
}
return View(newViewModel);

A quick guess based on the code you posted, is that you never instantiated the collection.
public class ViewModel1
{
List<Model1> model1;
public ViewModel1()
{
model1=new List<Model1>();
}
}
......
newViewModel.model1.Add(nmodel);

Change your ViewModel as follows
ViewModel::::
public class ViewModel1
{
public List<Model1> model1 = new List<Model1>();
}
Change your controller as follows:
var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
var nmodel = new Model1();
nmodel.Name = gf.Name;
nmodel.ProductName = doSomething(gf.ProductName);
newViewModel.model1.Add(nmodel);
}
return View(newViewModel);

Related

Blazorise DataGrid DataGridSelectColumn not recording change

I am trying to add select in blazorise component. Somehow it not showing me dropdown selected values. Please go through below code
Temp.razor file
#page "/temp"
#using Blazorise.DataGrid
<h3>TempComponent</h3>
<DataGrid TItem="ClassA"
Data="#Classes"
Editable="true"
RowUpdated="#OnRowUpdatedAsync">
<DataGridCommandColumn >
<EditCommandTemplate>
<Blazorise.Button Clicked="#context.Clicked"><Icon Name="IconName.Edit" /></Blazorise.Button>
</EditCommandTemplate>
<SaveCommandTemplate>
<Blazorise.Button Clicked="#context.Clicked"><Icon Name="IconName.Save" /></Blazorise.Button>
</SaveCommandTemplate>
</DataGridCommandColumn>
<DataGridColumn TItem="ClassA" Field="#nameof(ClassA.Name)" Caption="Name" Editable="true"/>
<DataGridSelectColumn TItem="ClassA" Field="#nameof(ClassA.B)" Caption="B" Editable="true">
<DisplayTemplate>
#if (#context.B != null)
{
#context.B.Name
}
</DisplayTemplate>
<EditTemplate>
<Select TValue="int" SelectedValue="#selectValue"
SelectedValueChanged="#SelectedValueChangedHandler">
#if (ClassesB != null)
{
foreach (var classB in ClassesB)
{
<SelectItem Value="#(classB.Id)">#(classB.Name)</SelectItem>
}
}
</Select>
</EditTemplate>
</DataGridSelectColumn>
</DataGrid>
#code{
int selectValue = 0;
public class ClassA {
public string Name { get; set; }
public ClassB B { get; set;}
}
public class ClassB {
public int Id { get; set; }
public string Name { get; set; }
}
List<ClassA> Classes = new List<ClassA> {
new ClassA { Name = "Class1", B = new ClassB() { Id = 1, Name = "ClassB1" }},
new ClassA { Name = "Class2", B = new ClassB() { Id = 2, Name = "ClassB2" }}
};
List<ClassB> ClassesB = new List<ClassB> {
new ClassB { Id = 1, Name = "ClassB1" },
new ClassB { Id = 2, Name = "ClassB2" }
};
protected void OnRowUpdatedAsync(SavedRowItem<ClassA, Dictionary<string, object>> e)
{
}
private void SelectedValueChangedHandler(int value)
{
Console.WriteLine("values " + value);
selectValue = value;
}
}
And Current Output Screenshot (select dropdown value not showing )
Whenever user select column then value should be change in list and also display in datagrid.
For this I took reference from https://github.com/Megabit/Blazorise/issues/561
Please help me to solve this issue .
Thanks in advance

linq to entity on dbcontext.set<>

I have multiple databases, 1 common and n company db. I use code first with one migration for common and one for the companies db.
I have a base context this is inherit to 2 contexts (common, company). I try to use only the base context and remove the specified contexts, so far no problem.
My problem is following, if i try to use linq on context.Set<> then I get an InvalidOperationException "The entity type NOCompany is not part of the model for the current context".
using (NOContext db = new NOContext(connection)) {
var dbset = db.Set<NOCompany>()
.Where(company => (company.Deleted == null) || (company.Deleted == false));
foreach (var item in dbset) {
System.Diagnostics.Debug.WriteLine(item.Matchcode);
}
}
if I use this
using (NOContext db = new NOCommonContext(connection)) {
var dbset = db.Set<NOCompany>()
.Where(company => (company.Deleted == null) || (company.Deleted == false));
foreach (var item in dbset) {
System.Diagnostics.Debug.WriteLine(item.Matchcode);
}
}
then it works fine. Where is the problem?
Following excerpt from the classes
public class NOContext : DbContext, INOContext
{
public NOContext() { }
public NOContext(string connection) : base(connection) { }
#region - override DbContext -
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<EntityBase>()) {
DateTime currentDateTime = DateTime.Now;
var entity = entry.Entity;
if (entry.State == EntityState.Added) {
entity.CreateDate = currentDateTime;
entity.CreateId = NOEngine.SessionInfo.CurrentUserId;
} else if (entry.State == EntityState.Deleted) {
entry.State = EntityState.Modified;
entity.Deleted = true;
entity.DeletedDate = currentDateTime;
entity.DeletedId = NOEngine.SessionInfo.CurrentUserId;
}
entity.ModifiedDate = currentDateTime;
entity.ModifiedId = NOEngine.SessionInfo.CurrentUserId;
}
return base.SaveChanges();
}
#endregion
//database methods
}
Then I have 2 specified context
public class NOCommonContext : NOContext
{
public const string CommonCatalog = "NOCommonDb";
public NOCommonContext() { }
public NOCommonContext(string connection) : base(connection) { }
#region - DbSets -
public virtual DbSet<NOUser> Users { get; set; }
public virtual DbSet<NOCompany> Companies { get; set; }
public virtual DbSet<NOConfig> AppConfiguration { get; set; }
#endregion //DbSets
}
and
public partial class NOAppContext : NOContext
{
public NOAppContext() { }
public NOAppContext(string connection) : base(connection) { }
#region - DbSets -
public virtual DbSet<BPCard> BPCards { get; set; }
public virtual DbSet<BPContact> BPContacts { get; set; }
public virtual DbSet<HRCard> HRCards { get; set; }
#endregion //DbSets
}

TryGetObjectByKey() doesn't return entity with Added state (EF 6)

1. Q #1
I have POCO
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public ICollection<Version> Versions { get; set; }
}
In my DbContext I have func
public void AttachUpdated<T>( T objectDetached) where T : class
{
var objContext = ((IObjectContextAdapter)this).ObjectContext;
var objSet = objContext.CreateObjectSet<T>();
var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, objectDetached);
object original;
if (objContext.TryGetObjectByKey(entityKey, out original))
objContext.ApplyCurrentValues(entityKey.EntitySetName, objectDetached);
else
objContext.AddObject(entityKey.EntitySetName, objectDetached);}
So i want to add some Products to context
var p1 = new Product(){Id = "1", Name = "Product 1";}
var p2 = new Product(){Id = "1", Name = "Product 1";}
ctx.AttachUpdated(p1);
And when i try to add identical Product (with same Id as first product) TryGetObjectByKey() doesn't find already added product.
ctx.AttachUpdated(p2);
Therefore I need to use ctx.SaveChanges() or AccseptAllChanges() and then
ctx.AttachUpdated(p2) work as expected.
I can't understand where i have problem in my code.
Q #2
var p1 = new Product() { Id = "1", Name = "Product 1" };
var v1 = new Version() { Number = "1.0", Type = "Release", ReleaseDate = "01/01/13" };
p1.Versions = new List<Version>();
p1.Versions.Add(v1);
ctx.AttachUpdated(p1);
And then i see that v1 was addet to DbSet(). But why? And how i could prevent such bihavior. I need to add only Product and not related Versions.
public void AttachOrUpdate<T>(T entity) where T : class
{
var objContext = ((IObjectContextAdapter)context).ObjectContext;
var objSet = objContext.CreateObjectSet<T>();
var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);
var original = this.context.Set<T>().Find(entityKey.EntityKeyValues[0].Value);
if (original != null)
{
this.context.Entry<T>(original).CurrentValues.SetValues(entity);
}
else
objContext.AddObject(entityKey.EntitySetName, entity);
}

Entity Framework , how to only validate specify property

I have a demo class "User" like the following:
public partial class User {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(30)]
[Required]
public string LoginName { get; set; }
[StringLength(120)]
[Required]
[DataType(DataType.Password)]
public string Pwd { get; set; }
[StringLength(50)]
public string Phone { get; set; }
[StringLength(100)]
public string WebSite { get; set; }
...
...
}
As you can see, "LoginName" and "Pwd" are "Required".
Some time , I only want to update user's "WebSite" , So I do like this:
public void UpdateUser(User user , params string[] properties) {
this.rep.DB.Users.Attach(user);
this.rep.DB.Configuration.ValidateOnSaveEnabled = false;
var entry = this.rep.DB.Entry(user);
foreach(var prop in properties) {
var entProp = entry.Property(prop);
//var vas = entProp.GetValidationErrors();
entProp.IsModified = true;
}
this.rep.DB.SaveChanges();
this.rep.DB.Configuration.ValidateOnSaveEnabled = true;
}
Parameter "user" like this:
new User(){
ID = 1,
WebSite = "http://www.stackoverflow.com"
}
Notice , I don't specify "LoginName" and "Pwd"
This function can work fine , but I wouldn't set ValidateOnSaveEnabled to false.
Is there any way only validate "WebSite" when ValidateOnSaveEnabled is true?
Thanks.
As I know validation executed in SaveChanges always validates the whole entity. The trick to get selective validation for property is commented in your code but it is not part of the SaveChanges operation.
I get a solution.
First define PartialValidationManager:
public class PartialValidationManager {
private IDictionary<DbEntityEntry , string[]> dics = new Dictionary<DbEntityEntry , string[]>();
public void Register(DbEntityEntry entry , string[] properties) {
if(dics.ContainsKey(entry)) {
dics[entry] = properties;
} else {
dics.Add(entry , properties);
}
}
public void Remove(DbEntityEntry entry) {
dics.Remove(entry);
}
public bool IsResponsibleFor(DbEntityEntry entry) {
return dics.ContainsKey(entry);
}
public void ValidateEntity(DbEntityValidationResult result) {
var entry = result.Entry;
foreach(var prop in dics[entry]){
var errs = entry.Property(prop).GetValidationErrors();
foreach(var err in errs) {
result.ValidationErrors.Add(err);
}
}
}
}
2, Add this Manager to My DbContext:
public class XmjDB : DbContext {
public Lazy<PartialValidationManager> PartialValidation = new Lazy<PartialValidationManager>();
protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry , IDictionary<object , object> items) {
if(this.PartialValidation.Value.IsResponsibleFor(entityEntry)) {
var result = new DbEntityValidationResult(entityEntry , new List<DbValidationError>());
this.PartialValidation.Value.ValidateEntity(result);
return result;
} else
return base.ValidateEntity(entityEntry , items);
}
...
...
Update Method :
public void UpateSpecifyProperties(T t, params string[] properties) {
this.DB.Set<T>().Attach(t);
var entry = this.DB.Entry<T>(t);
this.DB.PartialValidation.Value.Register(entry , properties);
foreach(var prop in properties) {
entry.Property(prop).IsModified = true;
}
this.DB.SaveChanges();
this.DB.PartialValidation.Value.Remove(entry);
}
Ok, it work fine.

Optgroup drop-down support in MVC - Problems with Model Binding

I wonder if anyone can shed some light on this problem..
I've got an option group drop-down for selecting a person's ethnicity – however it’s not storing the value in the model.
ViewModel
[UIHint("EthnicOriginEditorTemplate")]
[DisplayName("Question 6: Ethnic Origin")]
public int EthnicOrigin { get; set; }
Helper : GroupDropList.Cs
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
namespace Public.Helpers
{
public static class GroupDropListExtensions
{
public static string GroupDropList(this HtmlHelper helper, string name, IEnumerable<GroupDropListItem> data, int SelectedValue, object htmlAttributes)
{
if (data == null && helper.ViewData != null)
data = helper.ViewData.Eval(name) as IEnumerable<GroupDropListItem>;
if (data == null) return string.Empty;
var select = new TagBuilder("select");
if (htmlAttributes != null)
select.MergeAttributes(new RouteValueDictionary(htmlAttributes));
select.GenerateId(name);
var optgroupHtml = new StringBuilder();
var groups = data.ToList();
foreach (var group in data)
{
var groupTag = new TagBuilder("optgroup");
groupTag.Attributes.Add("label", helper.Encode(group.Name));
var optHtml = new StringBuilder();
foreach (var item in group.Items)
{
var option = new TagBuilder("option");
option.Attributes.Add("value", helper.Encode(item.Value));
if (SelectedValue != 0 && item.Value == SelectedValue)
option.Attributes.Add("selected", "selected");
option.InnerHtml = helper.Encode(item.Text);
optHtml.AppendLine(option.ToString(TagRenderMode.Normal));
}
groupTag.InnerHtml = optHtml.ToString();
optgroupHtml.AppendLine(groupTag.ToString(TagRenderMode.Normal));
}
select.InnerHtml = optgroupHtml.ToString();
return select.ToString(TagRenderMode.Normal);
}
}
public class GroupDropListItem
{
public string Name { get; set; }
public List<OptionItem> Items { get; set; }
}
public class OptionItem
{
public string Text { get; set; }
public int Value { get; set; }
}
}
This is my EditorTemplate
<%# Import Namespace="Public.Helpers"%>
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int>"%>
<%=Html.GroupDropList("EthnicOrigin",
new[]
{
new GroupDropListItem
{
Name = "Ethnicity",
Items = new List<OptionItem>
{
new OptionItem {Value = 0, Text = "Please Select"}
}
},
new GroupDropListItem
{
Name = "a) White",
Items = new List<OptionItem>
{
new OptionItem {Value = 1, Text = "British"},
new OptionItem {Value = 2, Text = "Irish"},
new OptionItem {Value = 3, Text = "Other White (Please specify below)"}
}
},
--snip
}, Model, null)%>
And in the view I'm referencing it as:
<%=Html.EditorFor(x => x.EthnicOrigin, "EthnicOriginEditorTemplate")%>
However it's not passing through the selected Value into the model... has anyone experienced similar problems... many thanks in advance for some pointers.
Your select doesn't have a name attribute and so when you submit the form the selected value is not sent to the server. You need to add a name:
select.GenerateId(name);
select.MergeAttribute("name", name);
Just changed the helper class to get it work for MVC 3 and with nullable int.
Thanks a lot for the class, saves me plenty of time.
public static class GroupDropListExtensions
{
public static MvcHtmlString GroupDropList(this HtmlHelper helper, string name, IEnumerable<GroupDropListItem> data, int? SelectedValue, object htmlAttributes)
{
if (data == null && helper.ViewData != null)
data = helper.ViewData.Eval(name) as IEnumerable<GroupDropListItem>;
if (data == null) return new MvcHtmlString(string.Empty);
var select = new TagBuilder("select");
if (htmlAttributes != null)
select.MergeAttributes(new RouteValueDictionary(htmlAttributes));
select.GenerateId(name);
select.MergeAttribute("name", name);
var optgroupHtml = new StringBuilder();
var groups = data.ToList();
foreach (var group in data)
{
var groupTag = new TagBuilder("optgroup");
groupTag.Attributes.Add("label", helper.Encode(group.Name));
var optHtml = new StringBuilder();
foreach (var item in group.Items)
{
var option = new TagBuilder("option");
option.Attributes.Add("value", helper.Encode(item.Value));
if (SelectedValue != 0 && item.Value == SelectedValue)
option.Attributes.Add("selected", "selected");
option.InnerHtml = helper.Encode(item.Text);
optHtml.AppendLine(option.ToString(TagRenderMode.Normal));
}
groupTag.InnerHtml = optHtml.ToString();
optgroupHtml.AppendLine(groupTag.ToString(TagRenderMode.Normal));
}
select.InnerHtml = optgroupHtml.ToString();
return new MvcHtmlString(select.ToString(TagRenderMode.Normal));
}
}
public class GroupDropListItem
{
public string Name { get; set; }
public List<OptionItem> Items { get; set; }
}
public class OptionItem
{
public string Text { get; set; }
public int Value { get; set; }
}
This is supported natively using SelectListGroup as of ASP.NET MVC 5.2:
var items = new List<SelectListItem>();
var group1 = new SelectListGroup() { Name = "Group 1" };
items.Add(new SelectListItem() { Text = "Item1", Group = group1 });
Then in MVC, do
#Html.DropDownList("select", items)