Reputation: 449
I have a data table I am rendering to a web page. I want to display a checkbox on each row. However when I try to display it is shows the html. Is there any way around this?
Class definition:
public int analysisId { get; set; }
public string heatName { get; set; }
public DateTime analysisTime { get; set; }
public string sampleType { get; set; }
public string grade { get; set; }
public string productId { get; set; }
public string element { get; set; }
public float value { get; set; }
The code in my model is below:
DataTable GridData = new DataTable();
GridData.Columns.Add("CheckBoxes");
GridData.Columns.Add("Analysis ID");
GridData.Columns.Add("Analysis Time");
GridData.Columns.Add("Sample Type");
GridData.Columns.Add("Product ID");
foreach (var item in elementheaders)
{
GridData.Columns.Add(item.Trim());
}
int gridend = GridData.Columns.Count;
int gridrow = 0;//x
int listrow = 0;//z
int checknum = 0;
foreach (int analysis in ChemList.Select(d => d.analysisId).Distinct())
{
DataRow dr = GridData.NewRow();
GridData.Rows.Add(dr);
GridData.Rows[gridrow][0] = System.Web.HttpUtility.HtmlDecode("<input type='checkbox' id="+checknum+">");
GridData.Rows[gridrow][1] = ChemList[listrow].analysisId;
GridData.Rows[gridrow][2] = ChemList[listrow].analysisTime;
GridData.Rows[gridrow][3] = ChemList[listrow].sampleType;
GridData.Rows[gridrow][4] = ChemList[listrow].productId;
}
In my view:
<div id="grid">
<table id="example" class ="gridTable">
<thead class="gridHead">
<tr>
@Html.DisplayFor(x => x.Columns)
</tr>
</thead>
<tbody>
@Html.DisplayFor(x => x.Rows)
</tbody>
</table>
</div>
Display Template for cells:
@model TheManhattanProject.Models.CellValueViewModel
<td>
@Html.DisplayFor(x => x.Value)
</td>
Display Template for Rows:
@model TheManhattanProject.Models.RowViewModel
<tr>
@Html.DisplayFor(x => x.Values)
</tr>
Display Template for Columns:
@model TheManhattanProject.Models.ColumnViewModel
<th>
@Html.DisplayFor(x => x.Name)
</th>
I have two view models for rendering this. One for each cell and row. The row is composed of a list of cell values.
Upvotes: 2
Views: 2328
Reputation: 449
Figured out the answer. It's an extension of what Matthew was trying to tell me.
@using System;
@model TheManhattanProject.Models.CellValueViewModel
<td>
@{if(Model.Value.StartsWith("<input type='checkbox'"))
{
@Html.Raw(Model.Value);
}
else
{
@Html.DisplayFor(x => x.Value);
}
}
</td>
Upvotes: 0
Reputation: 15931
You can use a customized display template for checknum that doesn't html encode.
Your ViewModel would use:
GridData.Rows[gridrow][0] = checknum;
The display template would use
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Int>" %>
<input type="checkbox" id="@Model" />
Upvotes: 1