I want to add an id to the "tr" elements of the mvccontrib grid I build:
<tr id="0"/>
<tr id="1"/>
so if the table contains 10 rows, the ids are 0 through to 9.
One way is to add an additional item to my entity to store this value and then create this as a hidden column with the id as the value of this item - not very elegant.
Is there a more elegant way to do this?
Thanks
I've got this far but now it complains at the RenderUsing line, any ideas?
#model IEnumerable<Tens.Models.UserPreviousNamesView>
<div class="demo_jui">
#{
var userId = 0;
foreach (var item in Model)
{
userId = item.Id;
break;
}
#(Html.Grid(Model.Select((item,index) => new { Item = item, Index = index}))
.Columns(col =>
{
col.For(p => p.Item.Title);
col.For(p => p.Item.Name);
col.Custom(#<text>
#Ajax.ActionLink("Delete", "DeleteUserPreviousName", "Summary", null, null, new { id = item.Item.Id, #class = "deleteUserPreviousName" })
</text>).Encode(false);
})
.RowAttributes(p => new Hash(Id => "id"+p.Item.Index.ToString()))
.Attributes(Id => "userPreviousNamesTable")
.Empty("You currently have no Previous Names.")
.RenderUsing(new Tens.GridRenderers.UserPreviousNamesGridRenderer<Tens.Models.UserPreviousNamesView>()));
}
You could transform the model to add it a row index and then use the RowAttributes method:
#model IEnumerable<MyViewModel>
#(Html
.Grid(Model.Select((item, index) => new { Item = item, Index = index }))
.Columns(column =>
{
column.For(x => x.Item.Foo);
column.For(x => x.Item.Bar);
})
.RowAttributes(x => new Hash(id => string.Format("id{0}", x.Item.Index)))
)
Also I have pre-pended the id with the id keyword as ids in HTML cannot statr with a number as shown in your example.
Sample output:
<table class="grid">
<thead>
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody>
<tr id="id0" class="gridrow">
<td>foo 1</td>
<td>bar 1</td>
</tr>
<tr id="id1" class="gridrow_alternate">
<td>foo 2</td>
<td>bar 2</td>
</tr>
<tr id="id2" class="gridrow">
<td>foo 3</td>
<td>bar 3</td>
</tr>
</tbody>
</table>
You can always show hide columns without adding id to particular row or columns like below
$(".mvcGridDollarHeader th:nth-child(16)").hide();
$(".mvcGrid td:nth-child(16)").hide();
Where mvcGrid is tableStyle and mvcGridDollarHeader is header style.
#grid1.GetHtml(
tableStyle: "mvcGrid",
displayHeader: true,
emptyRowCellValue: "",
headerStyle: "mvcGridDollarHeader",
Related
I am trying to implement a feature where a user would be able to add new columns and rows to a table using vue js. I am able to push a tag to the table however the method I'm using to add the I don't think its the right way especially since the td's are being added to the object but only to the view itself.
I am pulling the default html table content from laravel's helper file
(object)array(
'label' => 'Table',
'field_name' => '',
'type' => 'table',
'properties' => (object)array(
'headers' => [
'Header 1',
],
'rows' => [
(object) array(
'value' => 'Row 1 content',
),
],
)
)
Html(vue js)
...
<div v-if="field.type == 'table'">
<pre>{{field.properties.headers}}</pre><br>
<pre>{{field.properties.rows}}</pre>
<table :class="`table ` + field.properties.style" :id="`table`+index">
<thead>
<tr>
<th v-for="(header, index) in field.properties.headers" v-if="header.length > 0">
{{header}}
<i class="fa fa-trash"></i>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in field.properties.rows" :key="index" id="default-row">
<td>{{row.value}}</td>
</tr>
</tbody>
</table>
<table>
<tr>
<td>
Add Column
Add Row
</td>
<td></td>
<td></td>
</tr>
</table>
</div>
...
Script(vue js)
...
methods: {
addTableColumn(properties, index) {
properties.headers.push('Column Heading');
$(`#table${index} #default-row`).append(`<td>Row Content</td>`);
},
removeTableColumn(properties, index) {
properties.headers.splice(index, 1);
properties.rows.splice(index, 1);
},
addTableRow(properties, index) {
// let columnCount = properties.headers.length;
// for(let i = 0; i < columnCount; i++) {
// properties.rows.push({'value': 'Row content'});
// }
// console.log(columnCount);
// console.log(index);
// rows.push({ 'value': 'Row column' });
$(`#table${index}`).append(`<tr>${$('#default-row').html()}</tr>`);
}
},...
View
As seen in the picture below, I clicked the "add column" button and only the heading itself is pushed to the array and not the new td content(Row content).
Here's the table structure:
<table class="tb-stock tb-option">
<tr>
<th class="bgc2">col1</th>
<th class="bgc2">col2</th>
<th class="bgc2">col3</th>
</tr>
<tr class="alt-row">
<th class="">2018/1/29</th>
<td class="">0.11</td>
<td class=" b-b">0.50</td>
</tr>
<tr class="alt-row">
<th class="">2018/1/30</th>
<td class="">0.22</td>
<td class=" b-b">0.55</td>
</tr>
</table>
I want to get all the elements below "tr" (including "th" and "td")
How can I use linq to achieve this ?
Problems locate at "..tr.Elements("td|th").."
code:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(ms, Encoding.UTF8);
List<List<string>> table =
doc.DocumentNode.SelectSingleNode("//table[#class='tb-stock tb-option']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() >= 1)
.Select(tr => tr.Elements("td|th").Select(td => td.InnerText).ToList())
.ToList();
You can use the following code for extracting inner texts of td or th elements I test it in my local the output is :
2018/1/29
0.11
0.50
2018/1/30
0.22
0.55
You can filter the elements in line :
// both td and th
.Where(node => "td|th".Contains(node.Name))
// only td
.Where(node => "td".Contains(node.Name))
The working code is :
HtmlDocument doc = new HtmlDocument();
doc.Load("test.html", Encoding.UTF8);
List<string> table =
doc.DocumentNode.SelectSingleNode("//table[#class='tb-stock tb-option']")
.Descendants("tr")
.Skip(1)
.Where(tr => tr.Elements("th").Count() >= 1)
.SelectMany(tr => tr.ChildNodes)
.Where(node => "td|th".Contains(node.Name))
.Select(node => node.InnerText)
.ToList();
foreach (var str in table)
{
Console.WriteLine(str);
}
This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 4 years ago.
I am trying to return table values of my view back to the controller to save on db but I keep getting null. I can post the values without problem and bind them to the view.
I cannot understand why, I am using a server side view model.
Is there any way to perform this?
View:
#model IEnumerable<MultiEdit.Models.TableViewModel>
#using (Ajax.BeginForm("Save", "UUTs", new AjaxOptions
{
HttpMethod = "Post",
}, new { id = "tableForm" }))
{
#Html.AntiForgeryToken()
<div class="row" style="padding-top:10px;">
<div class="col-lg-12">
<table class="table table-bordered table-striped ">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.IsChassis)
</th>
<th>
#Html.DisplayNameFor(model => model.Justification)
</th>
</tr>
</thead>
<tbody id="tblMultiEdit">
#foreach(var item in Model)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.CheckIsChassis)
</td>
<td>
#Html.EditorFor(modelItem => item.Justification)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
Controller:
public void Save(IEnumerable<TableViewModel> vm)
{
DoSomething();
}
You need to iterate through your collection with a for loop and index qualifier. Something like the below. The syntax is not exact but you should be able to see what I mean.
#for(var index = 0; index <= Model.Count - 1; index++)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => Model[index].CheckIsChassis)
</td>
<td>
#Html.EditorFor(modelItem => Model[index].Justification)
</td>
</tr>
}
This is required so the index can be used to create the unique id's of the Enumerable items and aids model binding
Hope that helps
I resolved it by using IList insead of IEnumerable.
View:
#model IList<MultiEdit.Models.TableViewModel>
#Html.CheckBoxFor(modelItem => modelItem[index].CheckIsChassis, new { #class = "form-control" })
Controller:
public void Save(IList<TableViewModel> vm)
{
var x = vm;
}
I have the following Razor lines for now:
<table border=1 cellpadding=3 cellspacing=1 rules="rows" frame="box">
<tr>
<th>Türkçe Söz Dizisi</th>
<th>English Word Sequence</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tr)
</td>
<td>
#Html.DisplayFor(modelItem => item.En)
</td>
<td>
#Html.ActionLink((String)#ViewBag.Edit, "Edit", new { id=item.ID }) |
#Html.ActionLink((String)#ViewBag.Delete, "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
However, I will add some columns automatically from the program to database table. I need a way to print this th's and td's accordingly. In short, I need a way to go through Model's dynamic columns. How can I achieve this?
EDIT: My Model type here is "Proposal". However, I want to reach dynamic attribute of Proposal.Type.Word(Tr, En, or any other added Language Enum). How can I?
#foreach (var item in Model) {
Type objectType = Type.GetType(typeof(RexamOneriSistemi.Models.Word).AssemblyQualifiedName);
System.Reflection.PropertyInfo[] fields = objectType.GetProperties();
<tr>
<td>#Html.DisplayFor(modelItem => item.ID)</td>
<td>#Html.DisplayFor(modelItem => item.Owner.Name)</td>
#foreach (System.Reflection.PropertyInfo f in fields) {
if (f.Name.ToString() == #HttpContext.Current.Session["Language"].ToString())
{
<td>
// What to do here exactly to get item.Type.Word.[dynamic attribute]?
</td>
}
</tr>
}
I can get Razor String
string s = "#Html.Displayfor(modelItem => item.Type.Word." + System.Web.HttpContext.Current.Session["Language"] + ")"
Resulting: #Html.Displayfor(modelItem => item.Type.Word.Tr)
Can I insert a string to be rendered as Razor Syntax? If yes, how?
I have tried this code and it works
<table border=1 cellpadding=3 cellspacing=1 rules="rows" frame="box">
<tr>
#{
Type objectType = Type.GetType(typeof(yourProjectNamespace.Models.Language).AssemblyQualifiedName);
System.Reflection.PropertyInfo[] fields = objectType.GetProperties();
foreach (System.Reflection.PropertyInfo f in fields)
{
<th> #f.Name.ToString() </th>
}
}
</tr>
#foreach (yourModelType item in Model) {
<tr>
foreach (System.Reflection.PropertyInfo f in fields)
{
<td>#Html.Display(f.Name.ToString())</td>
}
<td>
#Html.ActionLink((String)#ViewBag.Edit, "Edit", new { id=item.ID }) |
#Html.ActionLink((String)#ViewBag.Delete, "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
To get Assemply Qualified Name of your class , see this link here
Came across this question, wrote this maybe it will help someone else. This code will dynamically load your model into a table.
#model System.Collections.Generic.List<App.Client.Models.MyModel>
<table>
<thead>
<tr>
#foreach (var property in Model.GetType().GetGenericArguments()[0].GetProperties())
{
<th>#property.Name</th>
}
</tr>
</thead>
<tbody>
#foreach (var modelItem in Model)
{
<tr>
#foreach (var property in modelItem.GetType().GetProperties())
{
<td>#property.GetValue(modelItem)</td>
}
</tr>
}
</tbody>
</table>
I'm new with mvc and I have 2 dropdownlists and I need to bind second one by first one using mvc 3..
Code sample
#<table>
<tr>
<td>
#Html.DropDownList("Brands", Model.Brands, "Select Brand", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Models", Model.Models, "Select Model", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Devices", Model.Devices, "Select Device", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Systems", Model.Systems, "Select System", New With {.style = "width:150px;"})
</td>
</tr>
</table>
I need to fill Models by Brands and Fill Devices by Models.
any help please..
Thanks
In view:
#Html.DropDownListFor( x => x.Model, new SelectList( LookupUtils.GetModelsList(Model.Brand), "Value", "Text", Model.Model))
LookupUtils is a static class have:
public static List<SelectListItem> GetModelsList(int brand)
{
var dataContext = new YourDataContext( );
var data = dataContext.GetModelsFn(brand).ToList();
var result = ( from res in data
select new SelectListItem()
{
Text = res.modelName,
Value = res.modelId.ToString()
} ).ToList();
return result;
}
For dynamicly update some dropdown lists, you should use jQuery-Collapse plugin: http://github.com/danielstocks/jQuery-Collapse/