i have a list grid ,i am assiging the values to listGrid by some method in my app
like this
private ListGridRecord[] getData(UserRecord selectedClient) {
return new ListGridRecord[]{
new NameValueRecord(1, "US Siren", selectedClient.getClientsId()),
new NameValueRecord(2, "EN: Liste des identifiants", selectedClient.getClientId2()),
new NameValueRecord(3, "Account number", selectedClient.getClientId3()),
new NameValueRecord(4, "Partner number", selectedClient.getClientId4()),
new NameValueRecord(5, "REGON", selectedClient.getClientId5()),
new NameValueRecord(6, "US Siren*", selectedClient.getClientId6()) ,
new NameValueRecord(7, "TEST", selectedClient.getClientId7())
};
}
It works fine for me and shows the given values in the grid when the app runs .
Now i want to get these values which are displaying in the grid (Which user can also edit from the grid)
I can get the edited values like this
clientIdsGrid.setEditorCustomizer(new ListGridEditorCustomizer() {
public FormItem getEditor(ListGridEditorContext context) {
ListGridField field = context.getEditField();
if (field.getName().equals("value")) {
NameValueRecord record = (NameValueRecord) context.getEditedRecord();
But if a user dont even click on any record and just click save to save the values as it is.
How can i then get the data which is in my grid .
I am trying these
clientIdsGrid.getRecord(1);
clientIdsGrid.getRecords();
but this gives me a listGrid/listGridRecord , how can i then fetch the individual data on each row from them .
grid.addEditorExitHandler may help. Within it u can use:
grid.getEditValueAsString(row num, Column name) for getting new edited value.
If no new it will return null.
Related
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
My model contains an array of zip code items (IEnumerable<SelectListItem>).
It also contains an array of selected zip codes (string[]).
In my HTML page, I want to render each selected zip code as a drop down with all the zip code options. My first attempt did not work:
#foreach (var zip in Model.ZipCodes) {
Html.DropDownList( "ZipCodes", Model.ZipCodeOptions )
}
I realized that although that would produce drop downs with the right "name" attribute, it wouldn't know which element of ZipCodes holds the value for that particular box, and might just default to the first one.
My second attempt is what really surprised me. I explicitly set the proper SelectListItem's Selected property to true, and it still rendered a control with nothing selected:
#foreach (var zip in Model.ZipCodes) {
Html.DropDownList( "ZipCodes", Model.ZipCodeOptions.Select( x => (x.Value == zip) ? new SelectListItem() { Value = x.Value, Text = x.Text, Selected = true } : x ) )
}
There, it's returning a new IEnumerable<SelectListitem> that contains all the original items, unless it's the selected item, in which case that element is a new SelectListItem with it's Selected property set to true. That property is not honored at all in the final output.
My last attempt was to try to use an explicit index on the string element I wanted to use as the value:
#{int zipCodeIndex = 0;}
#foreach (var zip in Model.ZipCodes) {
Html.DropDownList( "ZipCodes[" + (zipCodeIndex++) + "]", Model.ZipCodeOptions )
}
That doesn't work either, and probably because the name is no longer "ZipCodes", but "ZipCodes[x]". I also received some kind of read-only-collection error at first and had to change the type of the ZipCodes property from string[] to List<string>.
In a forth attempt, I tried the following:
#for (int zipCodeIndex = 0; zipCodeIndex < Model.ZipCodes.Count; zipCodeIndex++)
{
var zip = Model.ZipCodes[zipCodeIndex];
Html.DropDownListFor( x => x.ZipCodes[zipCodeIndex], Model.ZipCodeOptions )
}
That produces controls with id like "ZipCodes_1_" and names like "ZipCodes[1]", but does not select the right values. If I explicitly set the Selected property of the right item, then this works:
#for (int zipCodeIndex = 0; zipCodeIndex < Model.ZipCodes.Count; zipCodeIndex++)
{
var zip = Model.ZipCodes[zipCodeIndex];
Html.DropDownListFor( x => x.ZipCodes[zipCodeIndex], Model.ZipCodeOptions.Select( x => (x.Value == zip) ? new SelectListItem() { Value = x.Value, Text = x.Text, Selected = true } : x ) )
}
However, the problem with that approach is that if I add a new drop downs in JavaScript and give them all the name "ZipCodes", then those completely override all the explicitly indexed ones, which never make it to the server. It doesn't seem to like mixing the plain "ZipCodes" name with explicit array elements "ZipCodes[1]", even though they map to the same variable when either is used exclusively.
In the U.I., user's can click a button to add a new drop down and pick another zip code. They're all named ZipCodes, so they all get posted to the ZipCodes array. When rendering the fields in the loop above, I expect it to read the value of the property at the given index, but that doesn't work. I've even tried remapping the SelectListItems so that the proper option's "Selected" property is true, but it still renders the control with nothing selected. What is going wrong?
The reason you first 2 snippets do not work is that ZipCodes is a property in your model, and its the value of your property which determines what is selected (not setting the selected value in the SelectList constructor which is ignored). Since the value of ZipCodes is an array of values, not a single value that matches one of the option values, a match is not found and therefore the first option is selected (because something has to be). Note that internally, the helper method generates a new IEnumerable<SelectListItem> based on the one you provided, and sets the selected attribute based on the model value.
The reason you 3rd and 4th snippets do not work, is due to a known limitation of using the DropDownListFor() method, and to make it work, you need to use an EditorTemplate and pass the SelectList to the template using AdditionalViewData, or construct a new SelectList in each iteration of the loop (as per your last attempt). Note that all it needs to be is
for(int i = 0; i < Model.ZipCodes.Length; i++)
{
#Html.DropDownListFor(m => m.ZipCodes[i],
new SelectList(Model.ZipCodeOptions, "Value", "Text", Model.ZipCodes[i]))
}
If you want to use just a common name (without indexers) for each <select> element using the DropDownList() method, then it needs to be a name which does not match a model property, for example
foreach(var item in Model.ZipCodes)
{
#Html.DropDownList("SelectedZipCodes",
new SelectList(Model.ZipCodeOptions, "Value", "Text", item))
}
and then add an additional parameter string[] SelectedZipCodes in you POST method to bind the values.
Alternatively, use the for loop and DropDownListFor() method as above, but include a hidden input for the indexer which allows non-zero based, non consecutive collection items to be submitted to the controller and modify you script to add new items using the technique shown in this answer
Note an example of using the EditorTemplate with AdditionalViewData is shown in this answer
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)
My problem is pretty simple. Lets say I have a dropdown with users.
in the database i have 3 fields for my user table:
user_id
user_name
user_firstname
in my MVC app i want to link those users to projects. so thats why i want the dropdown.
now, i want to have a selectlist, with the ID as the value, and the firstname AND lastname to be the 'text'
SelectList sl = new SelectList(users, "user_id", "user_name");
now how do i get the first name also in the text? this should be fairly easy, but seems it isnt...
Use LINQ to transform your list of users into a list of SelectListItem.
var selectOptions =
from u in yourUserQuery
select new SelectListItem {
Value = u.user_id,
Text = u.user_firstname + " " + u. user_name
};
You can then convert that to a SelectList however you see fit. I personally like to define a .ToSelectList() extension method for IEnumerable<SelectListItem>, but to each his own.
You need to build a list from your database in the format you need. Here is what I did after my database read into a DataTable,
IList<UsrInfo> MyResultList = new List<UsrInfo>();
foreach (DataRow mydataRow in myDataTable.Rows)
{
MyResultList.Add(new UsrInfo()
{
Usr_CD = mydataRow["USR_NR"].ToString().Trim(),
Usr_NA = mydataRow["USR_NA_LAST"].ToString().Trim() + " , " +
mydataRow["USR_NA_FIRST"].ToString().Trim()
});
}
return new SelectList(MyResultList, "Usr_CD", "Usr_NA");
I'm using .NET 3.5, MVC.
I want to use a set of string aliases to represent database values. i.e. when a user selects an option from a dropdown it actually sets the value as 0, 1, 2, etc. in the table, rather than the text shown in the dropdown itself.
e.g. I'm doing:
IdName[] Thing = new[] {
new IdName { Id = 0, Name = "No Selection" },
new IdName { Id = 1, Name = "Thing A9" },
new IdName { Id = 2, Name = "Thing C12" },
new IdName { Id = 3, Name = "Thing F4" }
};
MyDropDownList = new SelectList(Things, "Id", "Name",0);
and in the view:
<%= Html.DropDownList("MyDropDownList")%>
Now, this works just fine. What I can't get to work is displaying the value of the field in a 'details' view and showing "Thing C12" as the text instead of "2".
Also, is this the best way to go about this? I don't want to use the actual string in the database in case I modify the text on an entry (e.g. change the name of "Thing F4" to "Thing F5".) I'm totally open to some other ideas.
Thanks!
So you want your action method (that will store the user choice) to store the value rather than the alias shown on the Dropdown.
I think you have two options here.
1- On the server side by getting the value(the id) from your data source, eg: the Things[] array in your example.
public ActionResult StoreValueFromDropDown(string MyDropDownList) {
var id = Things.Single(thing => thing.Name == MyDropDownList).Id;
// here goes the code to sotre the id
}
2- on the client side by adding a hidden field that store the value of the Dropdown.
here is an example using jQuery(I didn't test it):
<input type="hidden" id="ThingId" />
,
$('#MyDropDownList').change(function(e){
$('#ThingId').value($('#MyDropDownList option:selected').attr('value'));
});
then you need to modify your action method to accept the value of that hidden field
public ActionResult StoreValueFromDropDown(int ThingId) {
// here goes the code to sotre the id
}