MVC Telerik Grid Conditional column Value? - grid

How can i get this work in MVC Telerik Grid Control
columns.Template(e =>
{
if (e.EndDate>DateTime.Now )
{
#Html.ActionLink("Stop", "StopMedication", "Medication",
new { id = e.PrescriptionID }, new { #class = "standard button" })
}
else {
#Html.ActionLink("Renew", "RenewMedication", "Medication",
new { id = e.PrescriptionID }, new { #class = "standard button" })
}
});

The following snippet should work perfectly fine in the Telerik Grid template column using Razor syntax:
columns.Template(
#<text>
#if (#item.EndDate > DateTime.Now)
{
#Html.ActionLink("Stop", "StopMedication", "Medication",
new { id = #item.PrescriptionID }, new { #class = "standard button" })
}
else
{
#Html.ActionLink("Renew", "RenewMedication", "Medication",
new { id = #item.PrescriptionID }, new { #class = "standard button" })
}
</text>
);
Taking use of the #<text></text> inside of the template, as well as using the #item object, which represents the current item (entity tied to the row) and it's properties, will allow you to have this template up and running.

Related

DotNet HighCharts Exporting in Web Forms Asp.net

I want to add new button in list of exporting of charts,
i want to perform something like that :
http://jsfiddle.net/3GNZC/189/
but using DotNet HighCharts,
i already Tried to do that:
DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart1")
.InitChart(new Chart
{
BorderColor = System.Drawing.Color.Gray,
Height = ChartHeight
});
chart.SetExporting(new Exporting
{
Buttons = new ExportingButtons()
{
ContextButton = new ExportingButtonsContextButton()
{
MenuItems = **what can i write here!**
}
},
Enabled = true,
});
my problem here that i can not add new MenuItems to ContextButton without deleting the options that already exist like(Download PNG Image,....)
Definitely it's a bug which requires the package developer intervention. I reported it directly to wrapper developer, so we need to wait for the decision. To workaround it, you can temporary paste the code below to your <script> tag in .cshtml, which adds the button globally to Highcharts object, and bypassing .Net.
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
#using Highsoft.Web.Mvc.Charts
<script type="text/javascript">
Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({
text: 'Add Issue ',
onclick: function() {
alert('OK');
}
function formatXAxis() {
return this.value; // clean, unformatted number for year
}
function formatYAxis() {
return this.value / 1000 + 'k';
}
</script>
#(Html.Highsoft().GetHighcharts(
new Highcharts
{
Title = new Title
{
Text = "US and USSR nuclear stockpiles"
},
Subtitle = new Subtitle
{
Text = "Source: <a href='http://thebulletin.metapress.com/content/c4120650912x74k7/fulltext.pdf'>thebulletin.metapress.com</a>"
},
XAxis = new List<XAxis>
{
new XAxis
{
AllowDecimals = false,
Labels = new XAxisLabels
{
Formatter = "formatXAxis"
}
}
},
YAxis = new List<YAxis>
{
new YAxis
{
Title = new YAxisTitle
{
Text = "Nuclear weapon states"
},
Labels = new YAxisLabels
{
Formatter = "formatYAxis"
}
}
},
Tooltip = new Tooltip
{
PointFormat = "{series.name} produced <b>{point.y:,.0f}</b><br/>warheads in {point.x}"
},
PlotOptions = new PlotOptions
{
Area = new PlotOptionsArea
{
PointStart = 1940,
Marker = new PlotOptionsAreaMarker
{
Enabled = false,
Symbol = "circle",
Radius = 2,
States = new PlotOptionsAreaMarkerStates
{
Hover = new PlotOptionsAreaMarkerStatesHover
{
Enabled = true
}
}
}
}
},
Series = new List<Series>
{
new AreaSeries
{
Name = "USA",
Data = #ViewData["usaData"] as List<AreaSeriesData>
},
new AreaSeries
{
Name = "USSR/Russia",
Data = #ViewData["russiaData"] as List<AreaSeriesData>
}
}
}
, "chart")
)

Apply color to ActionLink

I am trying to change the font of a ActionLink, however I cannot get it to change when I have , null at the end of it.
What I have tried:
#Html.ActionLink(" Verification |", "VerIndex", "MFC_Form", new { deviceID = item.DeviceID, type = "Verification", id = "Color" }, null)
window.onload = function () {
var x = "fontColor";
alert("color " + x);
if (x == "fontColor") {
$("#Color").css('color', "red");
}
else {
$("#Color").css('color', "green");
}
}
and
#Html.ActionLink(" Verification |", "VerIndex", "MFC_Form", new { deviceID = item.DeviceID, type = "Verification", style = "color:red" }, null)
and
#Html.ActionLink(" Verification |", "VerIndex", "MFC_Form", new { deviceID = item.DeviceID, type = "Verification", #class = "fontColor" }, null)
You cannot mix the routeValues and htmlAttributes parameters. These two must be distinct objects.
View
#Html.ActionLink(" Verification |", "VerIndex", "MFC_Form", new {deviceID = item.DeviceID, type = "Verification"}, new { #class = "text-red" })
CSS
.text-red {
color: red;
}
The generated link looks like this:
<a class="text-red" href="/MFC_Form/VerIndex?deviceID=1&type=Verification"> Verification |</a>

ModelStateErrors not showing up in ValidationSummary

I have two validations in my action like so:
if (viewModel.IssuePDFFile == null || viewModel.IssuePDFFile.ContentLength == 0)
{
ModelState.AddModelError("", "Please select a file to upload.");
if (selectedJournalId > 0)
{
return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId });
}
else
{
return RedirectToAction("CreateNewIssue",
new { journalId = selectedJournalId, journalName = viewModel.JournalName });
}
}
var fileInfo = new FileInfo(viewModel.IssuePDFFile.FileName);
if (!StaticData.AcceptedContentTypes.Contains(viewModel.IssuePDFFile.ContentType,
StringComparer.InvariantCultureIgnoreCase) ||
!fileInfo.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
{
ModelState.AddModelError("IssuePDFFile", "You can only select a PDF file.");
if (selectedJournalId > 0)
{
return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId });
}
else
{
return RedirectToAction("CreateNewIssue", new { journalId = selectedJournalId,
journalName = viewModel.JournalName });
}
}
And in my view, I have this:
#using (Html.BeginForm(...)
{
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
#*File*#
<div class="form-group">
#Html.LabelFor(model => model.IssuePDFFile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-12">
<input type="file" id="File" name="issuePDFFile" placeholder="Select a file to upload" />
#Html.ValidationMessageFor(model => model.IssuePDFFile, "", new { #class = "text-danger" })
</div>
</div>
...
}
Please note that the excludePropertyErrors argument in the call to the #Html.ValidationSummary extension is set to false in the hope that errors that I myself add to the model state errors collection using keys other than my property names will also show up in the summary.
However, the two error messages shown in the code snippet above do not show up anywhere, neither in the validation summary, nor in the ValidationFor place where I think at least one of them, the one I have added a key for, should show up?
It looks like you are performing a redirect after writing errors to your modelstate. Redirecting will loose the modelstate, as it is only valid for the lifetime of the request, which ends when you redirect.
The solution is to
return View(Model) //customise as necessary
rather than your current
return RedirectToAction()
Writing the response back to the client within the same reuqest will mean the Modelstate is available to use, and display the errors.

Persisting dates between FullCalendar and an index view

I'm working on a website, asp.net MVC kind of thing. On the home page, I have two alternate views. One is a jquery FullCalendar, and one is an index view, both displaying events from a database.
I can currently change the month being viewed in either, but I want to be able to link them up, so that for example changing to view april 2013 in the calendar and then clicking "index view" will take me to april 2013 in the index view, rather than the default.
My "GetEventsForCalendar" method is as follows:
[HttpPost]
public virtual ActionResult GetEventsForCalendar(long start, long end)
{
var startDateTime = start.ToDateTime();
var endDateTime = end.ToDateTime();
var listOfEvents = eventRepository.List.Where(e => e.ToDate >= startDateTime
&& e.FromDate <= endDateTime).ToList() .Select(eventSerialiser.SerialiseForFullCalendarJS);
return Json(listOfEvents);
}
But I can't find anywhere in the codebase where it is given these parameters. The only place the function is specified is in the calendar partial view scrips section:
#section scripts {
#Scripts.Render(Links.Bundles.Scripts.calendar)
#Scripts.Render(Links.Bundles.Scripts.events_calendar)
<script type="text/javascript">
$(document).ready(function() {
SohoHouse.EventsCalendar.setup("#Url.Action(MVC.Events.GetEventsForCalendar())");
})
</script>
}
I think the details of the month being viewed are persisted in a cookie, but I'm not sure how to access this from my index view.
If you need any other code then please ask, I'm very new to programming and stack overflow so I'm still not sure how to ask questions well :)
Managed to get this working in the end: abandoned the idea of a seperate view for the index, and instead used the jquery to create a table with a list view of the events. Then used a button to toggle between the two. For reference, the calander.js looked something like this:
var report = $("#report");
var calendar = $("#calendar .fc-content");
report.hide();
$("#toggle-view").click(function() {
calendar.toggle();
report.toggle();
$("#calendar").fullCalendar("refetchEvents");
$("#calendar").fullCalendar("render");
updateToggleButtonText();
});
function updateToggleButtonText() {
$("#toggle-view").text(report.is(":visible") ? "View Calendar" : "View List");
}
function setUpCalendar() {
$("#calendar").fullCalendar({
events: {
url: getEventsUrl,
type: "POST",
eventDataTransform: addReportRow
},
timeFormat: "H:mm{ - H:mm}",
allDayDefault: false,
eventBorderColor: "gray",
header: {
left: "prev,next",
center: "title",
right: null
},
weekMode: "variable",
loading: function(isLoading) {
if (isLoading) {
$("table#report > tbody:last").empty();
}
},
allDaySlot: false
});
}
function addReportRow(data) {
var calendarMonth = $("#calendar").fullCalendar("getDate").getMonth();
var startDate = new Date(data.start);
var endDate = new Date(data.end);
if (startDate.getMonth() > calendarMonth || endDate.getMonth() < calendarMonth) {
return null;
}
var tableDetails = [
data.title,
$.fullCalendar.formatDate(startDate, "dd MMMM yyyy"),
$.fullCalendar.formatDate(endDate, "dd MMMM yyyy"),
data.published ? "Published" : "Not Published"
];
var row = $("<tr></tr>");
for (var i = 0; i < tableDetails.length; i++) {
row.append($("<td></td>").text(tableDetails[i]));
}
$("table#report > tbody:last").append(row);
return data;
}
function gotoDateFromCookie() {
var calendarDate = $.cookie("calendarDate");
if (calendarDate !== null && calendarDate !== "Invalid Date") {
$("#calendar").fullCalendar("gotoDate", new Date(calendarDate));
$.cookie("calendarDate", null);
}
}
function storeDateAsCookie() {
var calendarDate = $("#calendar").fullCalendar("getDate");
$.cookie("calendarDate", calendarDate);
}
window.eventDropdownChanged = function() {
location.reload();
};
};

webgrid sort not working

I'm using webgrid to show data from my data base. The problem is that sort option is not working
Here is my webgrid code
#{
var grid = new WebGrid(Model, canPage:true ,canSort:true, rowsPerPage :4);
grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(tableStyle: "webGrid", htmlAttributes: new { id = "datatable" },
headerStyle: "webgrid-header",
selectedRowStyle : "webgrid-selected-row",
footerStyle : "webgrid-footer",
rowStyle: "webgrid-row-style",
alternatingRowStyle: "webgrid-alternating-row",
columns: grid.Columns(
grid.Column(header: "", format: (item) =>
Html.ActionLink("Détails", "Details", new { id = item.id_client }, new { #class = "details" }), style: "actions"),
grid.Column(header: "", format: (item) => Html.ActionLink("Modifier", "Edit", new { id = item.id_client }, new { #class = "modifier" }),style : "actions"),
grid.Column(header: "", format: (item) => Html.ActionLink("Supprimer", "Delete", new { id = item.id_client }, new { #class = "supprimer" }), style: "actions"),
grid.Column("Nom",canSort: true),
grid.Column("Prenom", "Prénom",canSort:true),
grid.Column("Email")));
}
You can try add the list of name columns for your webgrid, for example:
var grid = new WebGrid(canPage:true ,canSort:true, rowsPerPage :4);
grid.Bind(Model,columnNames: new[] { "Nom", "Prenom"}); //adding names of columns
grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(...
Sometimes web grid can't understand how bind your model with columns.
Yes, James's answer worked for me. The sort links were working for some of the columns and not others, adding the columnNames: made it work properly.
Steve

Resources