Optgroup drop-down support in MVC - Problems with Model Binding - asp.net-mvc-2

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)

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

How can get a list data of Google Sheets based on column names in Entity Framework

I'm modeling data search in Google Sheets using API (EF). I am currently connected to Google Sheets data. I also wrote a search based on RowId it's ok. Everything works fine. However I can't find data based on Id. Everything I have:
ItemGoogleSheet.cs
public class ItemGoogleSheet
{
public string Id { get; set; }
public string Name { get; set; }
}
ItemsGoogleSheetMapper.cs
public class ItemsGoogleSheetMapper
{
public static List<ItemGoogleSheet> MapFromRangeData(IList<IList<object>> values)
{
var items = new List<ItemGoogleSheet>();
foreach (var value in values)
{
ItemGoogleSheet item = new()
{
Id = value[0].ToString(),
Name = value[1].ToString(),
};
items.Add(item);
}
return items;
}
public static IList<IList<object>> MapToRangeData(ItemGoogleSheet item)
{
var objectList = new List<object>() { item.Id, item.Name };
var rangeData = new List<IList<object>> { objectList };
return rangeData;
}
}
ItemsGoogleSheetVATController.cs
public class ItemsGoogleSheetVATController : ControllerBase
{
const string SPREADSHEET_ID = "xxxx";
const string SHEET_NAME = "xx";
SpreadsheetsResource.ValuesResource _googleSheetValues;
public ItemsGoogleSheetVATController(GoogleSheetsHelper googleSheetsHelper)
{
_googleSheetValues = googleSheetsHelper.Service.Spreadsheets.Values;
}
[HttpGet("{rowId}")]
public IActionResult GetRowID(int rowId)
{
var range = $"{SHEET_NAME}!A{rowId}:AG{rowId}";
var request = _googleSheetValues.Get(SPREADSHEET_ID, range);
var response = request.Execute();
var values = response.Values;
return Ok(ItemsGoogleSheetMapper.MapFromRangeData(values).FirstOrDefault());
}
[HttpGet]
public IActionResult GetID(string id)
{
//How to get Data from Id
//return Ok();
}
}
My Google Sheets Data:
As in my description. I want to find Id = 0102 then it will output a list of results of: 0102, 01022101, 01022102
How can I get list of data based on Id column. Asking for any solutions from everyone. Thank you!
I have solved the problem. Thank you!

How to write an audit log entry per changed property with Audit.NET EntityFramework.Core

I'm trying to get the Audit:NET EntityFramework.Core extension to write an AuditLog entry per changed property.
For this purpose I've overidden the EntityFrameworkDataProvider.InsertEvent with a custom DataProvider.
The problem is, using DbContextHelper.Core.CreateAuditEvent to create a new EntityFrameworkEvent returns null.
The reason seems to be, at this point in the code execution DbContextHelper.GetModifiedEntries determines all EF Entries have State.Unmodified, even if they are clearly included in the EventEntry changes.
I'm trying to circumvent CreateAuditEvent by manually creating the contents is impossible due to private/internal properties.
Maybe there is an alternative solution to this problem I'm not seeing, i'm open to all suggestions.
Audit entity class
public class AuditLog
{
public int Id { get; set; }
public string Description { get; set; }
public string OldValue { get; set; }
public string NewValue { get; set; }
public string PropertyName { get; set; }
public DateTime AuditDateTime { get; set; }
public Guid? AuditIssuerUserId { get; set; }
public string AuditAction { get; set; }
public string TableName { get; set; }
public int TablePK { get; set; }
}
Startup configuration
Audit.Core.Configuration.Setup()
.UseCustomProvider(new CustomEntityFrameworkDataProvider(x => x
.AuditEntityAction<AuditLog>((ev, ent, auditEntity) =>
{
auditEntity.AuditDateTime = DateTime.Now;
auditEntity.AuditAction = ent.Action;
foreach(var change in ent.Changes)
{
auditEntity.OldValue = change.OriginalValue.ToString();
auditEntity.NewValue = change.NewValue.ToString();
auditEntity.PropertyName = change.ColumnName;
}
}
Custom data provider class
public class CustomEntityFrameworkDataProvider : EntityFrameworkDataProvider
{
public override object InsertEvent(AuditEvent auditEvent)
{
var auditEventEf = auditEvent as AuditEventEntityFramework;
if (auditEventEf == null)
return null;
object result = null;
foreach (var entry in auditEventEf.EntityFrameworkEvent.Entries)
{
if (entry.Changes == null || entry.Changes.Count == 0)
continue;
foreach (var change in entry.Changes)
{
var contextHelper = new DbContextHelper();
var newEfEvent = contextHelper.CreateAuditEvent((IAuditDbContext)auditEventEf.EntityFrameworkEvent.GetDbContext());
if (newEfEvent == null)
continue;
newEfEvent.Entries = new List<EventEntry>() { entry };
entry.Changes = new List<EventEntryChange> { change };
auditEventEf.EntityFrameworkEvent = newEfEvent;
result = base.InsertEvent(auditEvent);
}
}
return result;
}
}
Check my answer here https://github.com/thepirat000/Audit.NET/issues/323#issuecomment-673007204
You don't need to call CreateAuditEvent() you should be able to iterate over the Changes list on the original event and call base.InsertEvent() for each change, like this:
public override object InsertEvent(AuditEvent auditEvent)
{
var auditEventEf = auditEvent as AuditEventEntityFramework;
if (auditEventEf == null)
return null;
object result = null;
foreach (var entry in auditEventEf.EntityFrameworkEvent.Entries)
{
if (entry.Changes == null || entry.Changes.Count == 0)
continue;
// Call base.InsertEvent for each change
var originalChanges = entry.Changes;
foreach (var change in originalChanges)
{
entry.Changes = new List<EventEntryChange>() { change };
result = base.InsertEvent(auditEvent);
}
entry.Changes = originalChanges;
}
return result;
}
Notes:
This could impact performance, since it will trigger an insert to the database for each column change.
If you plan to use async calls to DbContext.SaveChangesAsync, you should also implement the InsertEventAsync method on your CustomDataProvider
The Changes property is only available for Updates, so if you also want to audit Inserts and Deletes, you'll need to add the logic to get the column values from the ColumnValues property on the event

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);
}

creating list of custom object in mvc2 controller

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);