CSS class on HTML Helper - css

So I have this CSS:
<style type="text/css">
.DontShrink { width: 135px; }
</style>
There's 3 elements on the page that I want to have this width (use this class). Here's how I added it to the 3 elements:
<%= Html.DropDownListFor(m => m.AmortizationType,
Chatham.Web.Models.Indications.DropDownData.AmortizationTypeDropList(),
new { #class = "DontShrink", propertyName = "AmortizationType", onchange = "UpdateField(this, false);showScheduleFields();" })%>
<%= Html.TextBox("AmortizationComponent_AmortizationEndDate", Model.AmortizationComponent.AmortizationEndDate.HasValue ? Model.AmortizationComponent.AmortizationEndDate.Value.ToString("dd-MMM-yyyy") : "", new { #class = "DontShrink", propertyName = "AmortizationComponent.AmortizationEndDate", onchange = "parseAndSetDt(this); ", dataType = "Date" })%>
<%= Html.TextBoxFor(m => m.AmortizationRate, new { #class = "DontShrink", propertyName = "AmortizationRate", onchange = "UpdateField(this);" })%>
It worked for the 3rd one, but for the first two nothing happens. Why?

Changed to this for the CSS:
.DontShrink { width: 135px !important; }

Related

Generating one new field in table (ASP.NET MVC)

I have View where I create interview with greeting and details
Here is table
CREATE TABLE [dbo].[Interviews] (
[Interview_Id] INT IDENTITY (1, 1) NOT NULL,
[Greeting] NVARCHAR (MAX) NULL,
[Detail] NVARCHAR (MAX) NULL,
[VacancyId] INT NULL,
PRIMARY KEY CLUSTERED ([Interview_Id] ASC),
CONSTRAINT [FK_Interviews_ToTable] FOREIGN KEY ([VacancyId]) REFERENCES [dbo].[Vacancies] ([VacancyId]) ON DELETE CASCADE
);
Here is my controller for this View
// Страница ввода приветствия и описания вакансии
[HttpGet]
public ActionResult WelcomeScreen()
{
// Формируем список команд для передачи в представление
SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
ViewBag.Teams = teams;
return View();
}
//Заносим инфу о вакансии в таблицу
[HttpPost]
public ActionResult WelcomeScreen(Interview interview)
{
db.Interview.Add(interview);
db.SaveChanges();
//Int32 id = interview.Interview_Id;
//TempData["id"] = id;
return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
}
Here is my View
#using (Html.BeginForm())
{
<div class="outer-div">
<div class="inner-div">
<div class="right-welcome-div">
<div class="right-grid-in-grid">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Vacancy.VacancyId, ViewBag.Teams as SelectList, new { #class = "greeting" })
#Html.ValidationMessageFor(model => model.VacancyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="main-left-div">
<div style="margin-left: 40px">
#Html.EditorFor(model => model.Greeting, new {htmlAttributes = new {#class = "greeting", data_bind = "textInput: Greeting", placeholder = "Приветствие", id="Greeting"}})
</div>
#Html.TextAreaFor(model => model.Detail, new { #class = "greeting2", data_bind = "textInput: Detail" })
</div>
</div>
<div class="left-welcome-div">
<div class="text-div" style="padding-top: 30px; word-break: break-all;">
<p style="font-size: 20px; margin-top: 20px; padding-left: 30px; padding-right: 40px; text-align: center;"><b><span data-bind="text: Greeting"/></b>
</p>
<p style="font-size: 20px; margin-top: 40px; padding-left: 30px; padding-right: 40px; text-align: center;"><span data-bind="text: Detail"/>
</p>
</div>
<div class="button-div" style="padding-top: 40px;">
<input style="float: right; margin-right: 30px; margin-top: 20px; border-radius: 12px; width: 200px;" type="submit" value="Создать" class="btn btn-default" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
function ViewModel() {
this.Greeting = ko.observable('');
this.Detail = ko.observable('');
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
}
When I click submit button it creates new empty row in Vacancies table.
I don't understand, why??
Why so?
Because you generate dropDownList with name Vacancy.VacancyId according the following code an it will create a instance of Vacancy in property of Interview and When you add Interview in dbContext, EF will create new row for Vacancy because interview.Vacancy is not null.
#Html.DropDownListFor(model => model.Vacancy.VacancyId, ViewBag.Teams as SelectList, new { #class = "greeting" })
Replace the code with this
#Html.DropDownListFor(model => model.VacancyId, ViewBag.Teams as SelectList, new { #class = "greeting" })

I am trying to pass a json file generated with a webservice to an NVD3 graph

I have posted a similar question. I am relatively new to ASP.NET and webservices. Thanks to the online community, I was able to attempt linking my webservice to my NVD3 stackArea graph. Everything works when I first save the json file then use it on my webform. However, I want to link the entire process. I feel that I am very close and would greatly appreciate the community's feedback. Here is my webform:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="css/nv.d3.css" rel="stylesheet" type="text/css">
<link href="Content/bootstrap.min.css" rel="stylesheet"/>
<link href="css/pikaday.css" rel="stylesheet" type="text/css" />
<link href="css/theme.css" rel="stylesheet" type="text/css" />
<link href="css/site.css" rel="stylesheet" type="text/css" />
<script src="scripts/Pikaday/moment.js" type="text/javascript" ></script>
<script src="scripts/Pikaday/pikaday.js" type="text/javascript"></script>
<script src="scripts/jquery-1.9.1.js"></script>
<script src="scripts/d3.min.js" charset="utf-8"></script>
<script src="scripts/nv.d3.min.js"></script>
<style>
.singleLabel{
min-height: 20px;
text-align: left;
font-size: large;
margin-bottom:2px;
}
.textBox{
border-left-width: 1px;
min-height: 20px;
text-align: center;
font-size: large;
margin-bottom:2px;
}
.textbox.dropDown{
text-align: right;
}
text {
font: 12px sans-serif;
}
html, body, #chart, svg{
margin: 0 1px;
height: 100%;
width: 100%;
}
#chart{
height: 70vh;
}
.nv-x text{
font-size: 20px;
}
.nv-y text{
font-size: 20px;
}
.nv-series text {
font-size: 20px;
}
.row {
font-size: 30px;
}
.column{
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="row"> Report from: 
<asp:TextBox ID="startDate" runat="server" columns="6" style="border:1px solid #ff0000"></asp:TextBox>
 To 
<asp:TextBox ID="endDate" runat="server" columns="6" style="border:1px solid #ff0000"></asp:TextBox>
 <input type="button" id="btGO" value="Go!" />
<%-- Date picker for start and end --%>
<script = "text/javascript">
var picker = new Pikaday({
field: document.getElementById("startDate"),
firstDay: 1,
format: "YYYY-MM-DD",
minDate: new Date('2000-01-01'),
maxDate: new Date('2020-12-31'),
yearRange: [2000,2020],
numberOfMonths: 2
});
</script>
<script = "text/javascript">
var picker = new Pikaday({
field: document.getElementById("endDate"),
firstDay: 1,
format: "YYYY-MM-DD",
minDate: new Date('2000-01-01'),
maxDate: new Date('2020-12-31'),
yearRange: [2000,2020],
numberOfMonths: 2
});
</script>
</div>
<div class="row">
<div class="col-lg-12">
<div id="chart">
<svg></svg>
</div>
</div>
</div>
<script>
<%--JQuery ensures that scripts run safely by waiting for all the required files to load first--%>
$(document).ready(function () {
$(document).on("click", "#btGO", function () {
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
$.ajax({
url: "dataWebService.asmx.cs/getTotalForDateInterval",
data: {
startDate: startDate,
endDate: endDate
},
dataType: "json"
}).done(function (data) {
d3.json(data, function (error, data) {
nv.addGraph(function () {
var chart = nv.models.stackedAreaChart()
.x(function (d) { return d[0] })
.y(function (d) { return d[1] })
.clipEdge(true)
.useInteractiveGuideline(true);
chart._options.controlOptions = ['Expanded', 'Stacked'];
chart.xAxis
.showMaxMin(true)
.tickFormat(function (d) { return d3.time.format('%x')(new Date(d)) });
chart.yAxis
.tickFormat(d3.format(',.0f'));
d3.select('#chart svg')
.datum(data)
.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
});
});
});
});
</script>
</form>
</body>
</html>
Here is my webservice:
[WebMethod]
public void getTotalForDateInterval(string startDate, string endDate)
{
string cs = ConfigurationManager.ConnectionStrings["vetDatabase_Wizard"].ConnectionString;
List<keyValues> master = new List<keyValues>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("sp_CountAndGroupByDate", con);
cmd.CommandType = CommandType.StoredProcedure;
//Linking SQL parameters with webmethod parameters
SqlParameter param1 = new SqlParameter()
{
ParameterName = "#startDate",
Value = startDate
};
SqlParameter param2 = new SqlParameter()
{
ParameterName = "#endDate",
Value = endDate
};
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
con.Open();
//Get time in milliseconds
DateTime start = DateTime.ParseExact(startDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime end = DateTime.ParseExact(endDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime utime = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
long startMilliseconds = (long)((start - utime).TotalMilliseconds);
long endMilliseconds = (long)((end - utime).TotalMilliseconds);
const long oneDayInMilliseconds = 86400000;
//Declare temp dictionary to store the lists
Dictionary<string, List<long[]>> temp = new Dictionary<string, List<long[]>>();
string[] buildings = { "SSB", "GEN", "LYM", "LUD", "GCC", "MAC", "MMB" };
//Create building lists and initialize them with individual days and the default value of 0
foreach (string building in buildings){
temp.Add(building, new List<long[]>());
for (long j = startMilliseconds; j <= endMilliseconds; j = j + oneDayInMilliseconds){
long[] timeTotal = { j, 0 };
temp[building].Add(timeTotal);
}
}
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//Remove time from dateTime2 and assign totals for appropriate date
string s = (rdr["dateOpened"].ToString()).Substring(0, 10);
DateTime dateOpened = DateTime.ParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
long time = (long)((dateOpened - utime).TotalMilliseconds);
long total = (long)Convert.ToInt32(rdr["total"]);
string buildingName = rdr["building"].ToString();
int index = temp[buildingName].FindIndex(r => r[0].Equals(time));
temp[buildingName][index][1] = total;
}
//add all the keyValue objects to master list
for (int i = 0; i < buildings.Length; i++)
{
keyValues kv = new keyValues();
kv.key = buildings[i];
kv.values = temp[kv.key];
master.Add(kv);
}
JavaScriptSerializer js = new JavaScriptSerializer();
//Serialize list object into a JSON array and write in into the response stream
Context.Response.Write(js.Serialize(master));
}
}

MVC validation only border highlight without text error message

Hello I would like to only highlight the border of the text box without any error message near it, I have tried the following, but it still adds a span tag, can I avoid adding a span tag? Thank you!
[Required(ErrorMessage = " ")]
[Display(Name = "Email")]
public string Email { get; set; }
view
#using (Html.BeginForm("Login", "Account", new {
ReturnUrl = ViewBag.ReturnUrl
}, FormMethod.Post, new {
#class = "navbar-form navbar-nav",
id = "userForm"
})) {
#Html.AntiForgeryToken()
<div class="form-group">
#Html.ValidationMessageFor(m => m.Email, "", new {
#class = "text-danger"
})
#Html.TextBoxFor(m => m.Email, new {
#class = "form-control input-sm",
#placeholder = "Email"
})
</div>
<div class="form-group">
#Html.ValidationMessageFor(m => m.Password, "", new {
#class = "text-danger"
}) #Html.PasswordFor(m => m.Password, new {
#class = "form-control input-sm",
#placeholder = "Password"
})
</div>
<input type="submit" value="Log in" class="btn btn-sm btnMain"/>
}
Before
1
After
2
Edit: Added view.
Decorate your Validation Summary with a class and add the style display:none; for that in CSS:
in View:
#Html.ValidationSummary("", new { #class = "text-danger hidevalidation" })
in CSS:
.text-danger .hidevalidation{
display:none;
}
What have worked for me is adding another class to ValidationMessageFor in order to disable the text message only in certain locations.
New view:
#using (Html.BeginForm("Login", "Account", new {
ReturnUrl = ViewBag.ReturnUrl
}, FormMethod.Post, new {
#class = "navbar-form navbar-nav",
id = "userForm"
})) {
#Html.AntiForgeryToken()
<div class="form-group">
#Html.ValidationMessageFor(m => m.Email, "", new {
#class = "text-danger nav-text-danger"
})
#Html.TextBoxFor(m => m.Email, new {
#class = "form-control input-sm",
#placeholder = "Email"
})
</div>
<div class="form-group">
#Html.ValidationMessageFor(m => m.Password, "", new {
#class = "text-danger nav-text-danger"
}) #Html.PasswordFor(m => m.Password, new {
#class = "form-control input-sm",
#placeholder = "Password"
})
</div>
<input type="submit" value="Log in" class="btn btn-sm btnMain"/>
}
They newly added class:
.nav-text-danger { display: none; }
in order to add the red border I have added/modified the following CSS class:
.input-validation-error { border: 2px solid #ff0000 !important; }
Special thanks to #stephen-muecke for helping me with this one

how to expand the size of the DataType.MultilineText

I have define the following on my Model class:-
[DataType(DataType.MultilineText)]
public string Description { get; set; }
On the view I have the following:-
<span class="f"> Description :- </span>
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
now the output will be a small text area, but it will not show all the text . so how I can control the size of the DataType.MultilineText ?
:::EDIT:::
I have added the following to the CSS file:-
.f {
font-weight:bold;
color:#000000;
}
.f textarea {
width: 850px;
height: 700px;
}
And I have defined this :-
<div >
<span class="f"> Description :- </span>
#Html.TextArea("Description")
#Html.ValidationMessageFor(model => model.Description)
</div>
But nothing actually changed regarding the multi-line display.
This worked for me, with DataType set to MultilineText in the model:
[DataType(DataType.MultilineText)]
public string Description { get; set; }
And in the View specifying the HTML attribute "rows":
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { rows = "4" } })
Generates HTML like that:
<textarea ... rows="4"></textarea>
A text area with 4 rows.
so how I can control the size of the DataType.MultilineText ?
You could define a class to the textarea:
#Html.TextArea("Description", new { #class = "mytextarea" })
and then in your CSS file:
.mytextarea {
width: 850px;
height: 700px;
}

How to search a Telerik MVC Grid based on ASP.NET MVC 2.0's ListBox's selected Values?

I have a Telerik MVC Grid where there is a column Names , Gender , Age . I am going to use a ListBox which is bound to Gender ( coming from SQL 2k8 Table" Person". I am using Entity Framework, POCO classes , Repository Pattern ). Then there is a Image button as " Search " .
When a user selects few values from ListBox and then hits the " Search" Button Telerik MVC Grid which is on the same page ( I am rendering a User control which has actual Telerik MVC Grid) should be populated .
how to do this ? how to pass the selected ListBox values back to controller Action " SearchPerson" . There is a way of doing this using JQuery . But i dont know how to do this . Please help me
EDIT : Code
<% using (Ajax.BeginForm("SearchVouDate", "ERA", new AjaxOptions { UpdateTargetId = "ProfileList", LoadingElementId = "LoadingImage", OnSuccess = "ShowMessage" }))
{ %>
<div class="SelectNPI" >
<div class="DivSelectNPI">
<input name="selection1" value="NPI" id="rdNPI" type="radio" onclick="toggleLayer(this.checked);" />
<%:Html.Label(Resources.Strings.SelectNPI) %>
<div id="ERANPI" style="display: none;" >
<%:Html.ListBoxFor(m => m.Eras.NPI, new MultiSelectList(Model.GetERAs, "NPI", "NPI", Model.NPIListBox), new { ID="NPIList", style = "width: 160px; height:50px" })%>
</div>
</div>
<div class="SelectPIN">
<input name="selection1" type="radio" id="rdPIN" value="PIN" onclick="toggleLayer1(this.checked);" />
<%:Html.Label(Resources.Strings.SelectPIN) %>
<div id="ERAPIN" style="display: none;" >
<%:Html.ListBoxFor(m => m.Eras.PIN, new MultiSelectList(Model.GetERAs, "PIN", "PIN", Model.PINListBox), new {ID="PINList", style = "width: 180px; height:50px" })%>
</div>
</div>
</div>
<input type="submit" class="btnSearchSubmit" id="PaySearchDateSubmit" name="PaySearchDateSubmit" value="Search" />
</div>
</div>
<%} %>
<br /><br />
<div class="ERATopDiv" > <label id="Label1" class="lblSearchResult"> Search By Check Number</label> </div>
<br />
<div class="ERATopDiv"><label id="Label3" class="lblSearchResult" >Search Result</label> </div>
<div id="ProfileList">
<%Html.RenderPartial("SearchVoucherNum"); %>
</div>
<div id="results">
</div>
</div>
<div id="EraPopupWindow">
</div>
My Controller :
[HttpPost]
public ActionResult SearchVouDate(ERAViewModel era, FormCollection formValues)
{
try
{
if (formValues["Eras.NPI"] != null)
{
era.NPIListBox = formValues["Eras.NPI"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] selectedNPI = era.NPIListBox;
ERAViewModel ervm = new ERAViewModel();
foreach (string NPI in selectedNPI)
{
ervm = this.WorkerService.SearchByNPI(formValues);
return PartialView("SearchVoucherNum", ervm);
}
}
else
{
ERAViewModel eras = this.WorkerService.SearchByPIN(era.Eras.PIN);
return PartialView("SearchVoucherNum", eras);
}
}
catch (Exception ex)
{
bool reThrow = ExceptionPolicyWrapper.HandleException(ex, ExceptionPolicies.MVCPolicy);
if (reThrow)
throw;
}
return null;
}
My PartialView which I am rendering on my main View ( Main View contains my ListBox and partialView contains my telerik MVC Grid )
<% Html.Telerik().Grid(Model.GetERAs)
.Name("ERA").TableHtmlAttributes(new { style = "height:20px" })
.Scrollable(scroll => scroll.Enabled(true))
.DataKeys(datakeys => datakeys.Add(m => m.EraId))
.Columns(columns =>
{
columns.Bound(m => m.NPI).Title(Resources.Strings.NPI).Width(150)
.HtmlAttributes(new { style = "text-align:center" })
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" });
columns.Bound(m => m.PIN).Title(Resources.Strings.PIN).Width(150)
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(m => m.GroupName).Title(Resources.Strings.GroupName).Width(150)
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(m => m.CheckNo).Title(Resources.Strings.CheckNo).Width(100)
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(m => m.VoucherNo).Title(Resources.Strings.VoucherNo).Width(150)
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(m => m.VoucherDate).Title(Resources.Strings.VoucherDate).Format("{0:dd/MM/yyyy}").Width(150)
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(m => m.PaymentDate).Title(Resources.Strings.PaymentDate).Format("{0:dd/MM/yyyy}").Width(150)
.HeaderHtmlAttributes(new { style = "color:black; margin:0 0 0 0; padding-left:15px; background-color:#BDBDBD; text-align:center; border-right:grey" })
.HtmlAttributes(new { style = "text-align:center" });
columns.Bound(m => m.NonHippaVoucherPath).Title(Resources.Strings.NonHippaVoucherPath).Width(150).Format(Ajax.ActionLink("View Non Hippa voucher", "GetPdffile", "ERA", new { Id = "{0}" }, new AjaxOptions() { UpdateTargetId = "EraPopupWindow", HttpMethod = "Get" }, new { Style = "color:#FF0070;" }).ToString().Replace("{", "{{").Replace("}", "}}")).Encoded(false);
columns.Bound(m => m.HippaVoucherPath).Title(Resources.Strings.HippaVoucherPath).Width(150).Format(Ajax.ActionLink("View Hippa voucher", "GetPdffile", "ERA", new { Id = "{0}" }, new AjaxOptions() { UpdateTargetId = "EraPopupWindow", HttpMethod = "Get" }, new { Style = "color:#FF0070;" }).ToString().Replace("{", "{{").Replace("}", "}}")).Encoded(false);
//columns.Bound(m => m.Non_hippa_voucher_path).HtmlAttributes("color:#8A2BE2").Format(Html.ActionLink("View Non Hippa voucher", "GetPdffile", "ERA", new { ID = "{0}" }, new { onclick = "return someFunction();", Style = "color:#8A2BE2" }).ToHtmlString()).Encoded(false).Title("").Width(150);
//columns.Bound(m => m.Hippa_voucher_path).HtmlAttributes("color:#8A2BE2").Format(Html.ActionLink("View Hippa voucher", "GetFile/", new { ID = "{0}", Style = "color:#8A2BE2" }, "ERA/").ToHtmlString()).Encoded(false).Title("").Width(150);
})
// .ClientEvents(clientEvents => clientEvents.OnDataBinding("dataBinding"))
.DataBinding(databinding => databinding.Ajax().Select("AjaxERA", "ERA"))
.EnableCustomBinding(true)
.Pageable(paging =>{paging.Enabled(true) ;paging.PageSize(5) ;})
.Sortable()
.Filterable()
.Footer(true)
.Render();
%>
The best way to do this is to use jQuery.
You need your listBox and to bind your grid in AJAX.
Here's some sample code I have in an application :
View
<div class="content-box-filter">
<label>Filter:</label>
<%= Html.DropDownList("Years", Model.Years) %>
</div>
<div class="content-box">
<div class="content-box-header">
<h3>News</h3></div>
<div class="content-box-content">
<%= Html.Telerik().Grid<News>()
.Name("Grid")
.Columns(colums =>
{
colums.Bound(c => c.Title).Title("Titre").ClientTemplate("<a href=\"" + Url.Action(MVC.News.Modifier()) + "/<#=IdValue#>\" ><#=Title#></a>");
colums.Bound(c => c.Title).Title("Inscriptions").ClientTemplate("<a href=\"" + Url.Action(MVC.News.Inscriptions()) + "/<#=IdValue#>\" >fichier excel</a>");
colums.Bound(c => c.Published).Title("Publiée").HeaderHtmlAttributes(new { #class = "center-text" }).HtmlAttributes(new { #class = "center-text" }).ClientTemplate("<img src=\"../Content/images/icons/<#=Published#>.png\" alt=\"<#=Published#>\" />");
colums.Bound(c => c.CreationDate).Title("Date").HeaderHtmlAttributes(new { #class = "center-text" }).HtmlAttributes(new { #class = "center-text" }).Format("{0:MM/dd/yyyy}");
colums.Bound(c => c.IdValue).Title(" ").HeaderHtmlAttributes(new { #class = "center-text" }).HtmlAttributes(new { #class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.News.Modifier()) + "/<#=IdValue#>\" title=\"Modifier\" ><img src=\"../Content/images/icons/pencil.png\" alt=\"Modifier\" /></a>");
colums.Bound(c => c.IdValue).Title(" ").HeaderHtmlAttributes(new { #class = "center-text" }).HtmlAttributes(new { #class = "center-text" }).Format("<a id=\"deleteLink{0}\" href=\"#\" title=\"Supprimer\" onclick=\"if(confirm('Voulez-vous vraiment supprimer cette nouvelle?')){ return deleteNews('{0}');} else { return false;};\"><img src=\"../Content/images/icons/cross.png\" alt=\"Supprimer\" /></a>");
})
.DataBinding(d => d.Ajax().Select("ListAjax", "News", new { year = DateTime.Now.Year }))
.Sortable()
%>
<%= Html.AntiForgeryToken() %>
</div>
</div>
<script type="text/javascript">
var token = $('[name=__RequestVerificationToken]').val();
$(document).ready(function() {
$('#Years').val(<%=DateTime.Now.Year%>);
$('#Years').change(function() {
var grid = $('#Grid').data('tGrid');
grid.rebind({ year: this.value });
});
});
function deleteNews(newsId) {
$.post('DeleteNews', { __RequestVerificationToken: token, id: newsId }, function(data) {
if (data == 'true') {
$('#deleteLink' + newsId).parent().parent().remove();
}
return false;
});
return false;
};
</script>
The NewsController action :
[GridAction]
public virtual ActionResult ListAjax(int year)
{
var gridModel = new GridModel<News>();
gridModel.Data = _newsRepo.GetByYear(year);
return View(gridModel);
}
Let me know if you still have question.

Resources