Create a column without no record in the database for a Grid in syncfusion "false column" MVC - asp.net-mvc

I am generating a grid from a view querying multiple tables. I need to add a column that will be edited by the user by entering an amount so that the row can save as a new record in a couple of tables. This is why the column is not really generated in the database, since there is not really a record that contains that amount.
#(Html.EJ().Grid<object>("ITEMS_PRESUPUESTOGrid")
.Datasource(ds => ds.URL("GetOrderData_VISTA_ITEMS_PRESUPUESTO_ACTIVO").Adaptor(AdaptorType.UrlAdaptor))
//.AllowScrolling()
//.ScrollSettings(col => { col.Width(520).Height(300).EnableVirtualization(true); })
.AllowPaging()
.AllowFiltering()
.QueryString("COD_SUBCAPITULO")
.Locale("es-CO")
.AllowResizeToFit(true)
.AllowResizing(false)
.AllowMultiSorting()
.AllowSorting()
.PageSettings(page => page.PageSize(7))
.ClientSideEvents(eve => eve.ToolbarClick("clickedderecha"))
.FilterSettings(filter => { filter.FilterType(FilterType.Excel); })
.EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Normal); })
.ClientSideEvents(e => e.Load("load_VISTA_ITEMS_PRESUPUESTO_ACTIVOGrid").Create("create_grid_ITEMS_PRESUPUESTOGrid").ActionBegin("inicio").ActionBegin("inicio_grid_VISTA_ITEMS_PRESUPUESTO_SIN_CONTRATOGrid").Create("create_grid_VISTA_ITEMS_PRESUPUESTO_SIN_CONTRATOGrid"))
.ToolbarSettings(toolbar =>
{
toolbar.ShowToolbar().ToolbarItems(items =>
{
items.AddTool(ToolBarItems.Search);
});
}).Columns(col =>
{
col.Field("COD_ITEM").HeaderText("CÓDIGO").IsPrimaryKey(true).Visible(true).Add();
col.Field("NOMBRE").HeaderText("NOMBRE").Add();
col.Field("CANTIDAD").HeaderText("C. PRESU.").Add();
col.HeaderText("C. A REG").EditType(EditingType.NumericEdit).Add();
})
to edit the data in the template (client side) I am trying with: .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Normal); }) but i don't know how to see these changes reflected. enter image description here after editing it is not saving the entered value.
The column in reference is the last one. At this time, first it is not taking the default value and it is not saving the value that I enter when I edit the column.
I have not yet created the function to save the data in the database because first I want to get to modify the data in the template.
This is the code for the database view:
CREATE VIEW [dbo].[VISTA_ITEMS_PRESUPUESTO_ACTIVO]
AS
SELECT
dbo.ITEMS_PRESUPUESTO.COD_ITEM,
dbo.ITEMS_PRESUPUESTO.NOMBRE, dbo.ITEMS_PRESUPUESTO.CANTIDAD,
dbo.PRESUPUESTOS_ITEM_PRESUPUESTO.COD_PRESUPUESTO_ITEM_PRESUPUESTO,
dbo.PRESUPUESTOS_ITEM_PRESUPUESTO.COD_PRESUPUESTO,
dbo.PRESUPUESTOS.COD_PROYECTO,
0 AS CANTIDAD_ACTIVIDAD
FROM
dbo.ITEMS_PRESUPUESTO INNER JOIN
dbo.PRESUPUESTOS_ITEM_PRESUPUESTO ON dbo.ITEMS_PRESUPUESTO.COD_ITEM = dbo.PRESUPUESTOS_ITEM_PRESUPUESTO.COD_ITEM
INNER JOIN
dbo.PRESUPUESTOS ON dbo.PRESUPUESTOS_ITEM_PRESUPUESTO.COD_PRESUPUESTO = dbo.PRESUPUESTOS.COD_PRESUPUESTO
INNER JOIN
dbo.PROGRAMAS ON dbo.PROGRAMAS.COD_PROYECTO = dbo.PRESUPUESTOS.COD_PROYECTO
WHERE (dbo.ITEMS_PRESUPUESTO.COD_ESTADO_ITEM_PRESUPUESTO = 1) AND (dbo.PRESUPUESTOS.COD_ESTADO_PRESUPUESTO = 5)
and this is the controller:
public ActionResult GetOrderData_VISTA_ITEMS_PRESUPUESTO_ACTIVO(DataManager dm)
{
IEnumerable DataSource = db.VISTA_ITEMS_PRESUPUESTO_ACTIVO.ToList();
DataOperations ds = new DataOperations();
List<string> str = new List<string>();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
return Json(new { result = DataSource }, JsonRequestBehavior.AllowGet);
}
if someone can help me I am very grateful

strong text
I found a solution in the official documentation
}).Columns(col => {
col.Type("checkbox").HeaderText("").Field("").Width("60").AllowFiltering(false).AllowSorting(false).Add();
col.Field("COD_ITEM").HeaderText("CÓDIGO").IsPrimaryKey(true).Visible(false).col.Field("NOMBRE").HeaderText("NOMBRE").Add();
col.Field("CANTIDAD").HeaderText("C. DISPONIBLE").Add();
col.HeaderText("C. ADD").Template("<input value=0 />").Add();
I added two editable fields, the check one and an input, I share the links to expand the information:
https://help.syncfusion.com/aspnetmvc/grid/columns?cs-save-lang=1&cs-lang=razor
https://help.syncfusion.com/aspnetmvc/grid/editing?_ga=2.162224380.1153013492.1605824141-52632355.1601061767#default-column-values-on-add-new

Based on your sample, the last column has no field properties. So the last column displays the empty value. Based on your query, you are using Multiple table to generate grid. So we suggest that you use foreign key column. Please refer to the below code snippet:
Your code:
col.Field("NOMBRE").HeaderText("NOMBRE").Add();
col.Field("CANTIDAD").HeaderText("C. PRESU.").Add();
col.HeaderText("C. A REG").EditType(EditingType.NumericEdit).Add();
.
Modified code:
col.Field("OrderID").HeaderText("CÓDIGO").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); col.Field("Freight").HeaderText("NOMBRE").TextAlign(TextAlign.Right).EditType(EditingType.NumericEdit).Width(75).Format("{0:C}").Add();
col.Field("ShipCity").HeaderText("C. PRESU.").Width(80).Add();
col.Field("EmployeeID").HeaderText("C. A REG").ForeignKeyField("EmployeeID").ForeignKeyValue("FirstName").DataSource(ViewBag.data).TextAlign(TextAlign.Right).Width(90).Add();
Please refer to the below help documentation:
https://help.syncfusion.com/aspnetmvc/grid/columns#foreign-key-column
Please refer to the modified sample:
https://www.syncfusion.com/downloads/support/directtrac/304148/ze/Grid-sample-627225723

Related

How to display the data of two tables in a view using LINQ lambda expression in ASP.Net MVC?

I'm having a hard time trying to display the data from two tables into a view using a linq lambda expression in ASP.net MVC.
I've tried this code:
var idSearchJoin = payoutdb.payout_transaction // your starting point - table in the "from" statement
.Join(payoutdb.payout_remittance, // the source table of the inner join
transaction => transaction.transid, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
remit => remit.transid, // Select the foreign key (the second part of the "on" clause)
(transaction, remit) => new { Transaction = transaction, Remit = remit }) // selection
.Where(transactremit => transactremit.Transaction.senderRefId == searchTxt).ToList();
I've joined the two tables but now my problem is that i can't put it into a view model to be able to display it to a view because the two tables have the same column transid so even if i created a new model to match the values of the result of linq expression it will not match because the transid cannot be initiated twice inside the same view model. Do you have any suggestions on how am i supposed to do this?
I am not sure what you mean by transid cannot be initiated twice. If you want to put your results set to your ViewModel, you need to put it right on your selection or after your query:
Instead of this:
(transaction, remit) => new { Transaction = transaction, Remit = remit }) // selection
Do this (MyViewModel is the name of my View Model):
(transaction, remit) => new MyViewModel()
{ field1 = transaction.transid, field2 = remit.whateverfield, field3 = transaction.whateverfield })
//selection, replace field1 with your correct fields
Then do the filtering (removed the Transaction word) :
.Where(transactremit => transactremit.senderRefId == searchTxt).ToList();

Removing duplicates from a dropdown list in mvc

So I was working on a DropDown list and it works, but it has many duplicate emails, I just want to see distinct emails... So I tried doing .Distinct() in the model class, but that still gave me duplicates..
Model Class:
public string One_Manager_Email{ get; set; }
public List<Hello> getManagers()
{
var que = (from wr in db.View
select new Hello
{
O_Manager_Email= wr.One_Manager_Email
}).Distinct().ToList();
return que;
}
Controller Class: (This is probably where the problem is happening)
public ActionResult Index()
{
test = new Hello();
ViewBag.Managers = new SelectList(test.getManagers(), "", "O_Manager_Email");
return View(test.getStuff());
}
View Class:
<div>
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
</div>
Any help would be great, thank you!
You need to group your objects by the property you want them to be distinct by, and then select the first element of the grouping.
public List<Hello> getManagers()
{
var que = (from wr in db.View
select new Hello
{
O_Manager_Email= wr.One_Manager_Email
})
.GroupBy(g => g.O_Manager_Email) //group by property
.Select(g => g.First()) //take first element from every grouping
.ToList();
return que;
}
For some more details, you can see this post that has more details on grouping and distinct: LINQ's Distinct() on a particular property
Distinct won't work on objects like that, as objects are always distinct, but you can try using group by in your query, something along these lines:
var que = (from wr in db.View
group new {wr.One_Manager_Email}
by new {wr.One_Manager_Email} into grouped
select new Hello
{
O_Manager_Email= grouped.Key.One_Manager_Email
}).ToList();
return que;
If you just need email address, you can select just string instead of selecting Hello object. If you select Hello object and try to distinct you like that way, you obviously get duplicated items. Because every object is already unique.
I believe you have already answer. GroupBy might solve your problem. However unless you really need GroupBy, don't use GroupBy! It's really expensive operation.
In your case, you should use DistinctBy.
var distinctList = list.DistinctBy(x => x.Prop).ToList();
On your code:
var que = (from wr in db.View
select new Hello
{
O_Manager_Email = wr.One_Manager_Email
}).DistinctBy(x=>x.O_Manager_Email).ToList();
Oh, in terms of DistinctBy usage, you should import namespace of Microsoft.Ajax.Utilities.
using Microsoft.Ajax.Utilities;

DropDownList in my edit view mvc

i have List view and in every rows it has the "Actualizar" link action and that one takes me to the edit view in which i have some dropdownLists available for updating my existing data but my big problem is that i want the dropdownlist to first load the data is save. how can i set the dropdownlist to load the data of the model a return and let me choose other options
controller:
public ActionResult ActualizarDispositivo(int id )
{
dropDown();
var equipo= _db.equipo.Include(m=>m.marca).Include(mo=>mo.modelo.Single(b => b.idEquipo==id);
ViewBag.idMarca = _db.marca.ToList().Select(Mar => new SelectListItem
{
Value = Mar.idMarca.ToString(),
Text = Mar.Descripcion.ToString(),
Selected = true
});
return View("ActualizarDispositivo",equipo);
}
in the edit view i have this
#Html.DropDownListFor(m=>m.idMarca,(IEnumerable<SelectListItem>)ViewBag.idMarca)
The code you are using should work, if you simply remove the Selected = true. Currently you are setting all of the DropDownList's values to selected.
I'm not sure which performs better, but I do find it more readable to create a select list using:
ViewBag.idMarca = new SelectList(_db.marca.ToList(), "idMarca", "Descripcion");
And then, there may be no need to cast. (Unsure, I avoid the use of ViewBag)
#Html.DropDownListFor(m=>m.idMarca, ViewBag.idMarca)

Static list of data for dropdown list MVC

I want to have a static list of data in a model that can be used in a viewmodel and dropdown on a view. I want to be able to use it in this way in my controller:
MaintenanceTypeList = new SelectList(g, "MaintenanceTypeID", "MaintenanceTypeName"),
and access it in my view like this:
#Html.LabelFor(model => model.MaintenanceTypeID)
#Html.DropDownListFor(x => x.MaintenanceTypeID, Model.MaintenanceTypeList, "-- Select --", new { style = "width: 150px;" })
#Html.ValidationMessageFor(x => x.MaintenanceTypeID)
I am currently using a repository pattern for data in the database, but don't want to put this data in the database because it will never change. I still want it in a model though. Basically, my dropdown list should offer the following:
Value Text
-------------------------------------
Calibration Calibration
Prevent Preventative Maintenance
CalibrationPrevent PM and Calibration
Any help or examples of static lists using models/oop is appreciated
You can use a list initializer:
public static SomeHelperClass{
public static List<SelectListItem> MaintenanceTypeList {
get {
return new List<SelectListItem>
{ new SelectListItem{Value = "Calibration", Text = "Calibration"}
,new SelectListItem{ Value = "Prevent", Text = "Preventative Maintenance" }
,etc.
};
}
}
}
Hopefully I didn't miss a curly brace somewhere. You can google "C# list initializer" for more examples. I don't remember off top of my head what the actual collection to is for a SelectListCollection is, but I know there is a overload of DropDownList that accepts List as I often just have a collection of keyvaluepairs or something else, and then in my view I convert it to SelectListItems: someList.Select(i => new SelectListItem { Value = i.Key, Text = i.Value })
Note that another option is to place your values in an enum. You can then use a Description attribute on each enum value:
enum MaintenanceType {
[Description("Calibration")]
Calibration = 1,
[Description("Preventative Maintenance")]
Prevent = 2
}
Then you can do things like
Enum.GetValues(typeof(MaintenanceType )).Select(m=>new SelectListItem{ Value = m, Text = m.GetDescription()} ).ToList()
That last line was a little off the top of the head, so hopefully I didn't make a mistake. I feel like an enum is more well structured for what you're trying to do.

Getting a list of distinct entities projected into a new type with extra field for the count

I'm designing an interface where the user can join a publicaiton to a keyword, and when they do, I want to suggest other keywords that commonly occur in tandem with the selected keyword. The trick is getting the frequency of correlation alongside the properties of the suggested keywords.
The Keyword type (EF) has these fields:
int Id
string Text
string UrlString
...and a many-to-many relation to a Publications entity-set.
I'm almost there. With :
var overlappedKeywords =
selectedKeyword.Publications.SelectMany(p => p.Keywords).ToList();
Here I get something very useful: a flattened list of keywords, each duplicated in the list however many times it appears in tandem with selectedKeyword.
The remaining Challenge:
So I want to get a count of the number of times each keyword appears in this list, and project the distinct keyword entities onto a new type, called KeywordCounts, having the same fields as Keyword but with one extra field: int PublicationsCount, into which I will populate the count of each Keyword within overlappedKeywords. How can I do this??
So far I've tried 2 approaches:
var keywordCounts = overlappingKeywords
.Select(oc => new KeywordCount
{
KeywordId = oc.Id,
Text = oc.Text,
UrlString = oc.UrlString,
PublicationsCount = overlappingKeywords.Count(ok2 => ok2.Id == oc.Id)
})
.Distinct();
...PublicationsCount is getting populated correctly, but Distinct isn't working here. (must I create an EqualityComarer for this? Why doesn't the default EqualityComarer work?)
var keywordCounts = overlappingKeywords
.GroupBy(o => o.Id)
.Select(c => new KeywordCount
{
Id = ???
Text = ???
UrlString = ???
PublicationsCount = ???
})
I'm not very clear on GroupBy. I don't seem to have any access to 'o' in the Select, and c isn't comping up with any properties of Keyword
UPDATE
My first approach would work with a simple EqualityComparer passed into .Distinct() :
class KeywordEqualityComparer : IEqualityComparer<KeywordCount>
{
public bool Equals(KeywordCount k1, KeywordCount k2)
{
return k1.KeywordId== k2.KeywordId;
}
public int GetHashCode(KeywordCount k)
{
return k.KeywordId.GetHashCode();
}
}
...but Slauma's answer is preferable (and accepted) because it does not require this. I'm still stumped as to what the default EqualityComparer would be for an EF entity instance -- wouldn't it just compare based on primary ids, as I did above here?
You second try is the better approach. I think the complete code would be:
var keywordCounts = overlappingKeywords
.GroupBy(o => o.Id)
.Select(c => new KeywordCount
{
Id = c.Key,
Text = c.Select(x => x.Text).FirstOrDefault(),
UrlString = c.Select(x => x.UrlString).FirstOrDefault(),
PublicationsCount = c.Count()
})
.ToList();
This is LINQ to Objects, I guess, because there doesn't seem to be a EF context involved but an object overlappingKeywords, so the grouping happens in memory, not in the database.

Resources