Download pdf files from kendo ui grid - asp.net-mvc-4

I have a table column called PDF(varbinary). The column will bind in kendo ui grid as hyperlink which download the pdf from the database.
The following is the code that i have so far. Based on the research i have done. Therefore i am implementing a template.
The italic code below showing said error "required )" and i am not quite sure what i am missing here.
columns.Template(#).ClientTemplate("Download file").Title("Download1");
Therefore I would kindly advise to implement the download file (pdf format) in kendo ui grid. Thank you
#(Html.Kendo().Grid<HH.Models.OrderModel>()
.Name("OrderGrid")
.HtmlAttributes(new { #Style = "align:center; font-size:10px; width:600px" })
.Columns(columns =>
{
columns.Bound(p => p.OrderId);
columns.Bound(p => p.Date).EditorTemplateName("Date").Format("{0:dd/MM/yyyy}");
columns.Bound(p => p.CustFullName).Width(120);
columns.Template(#<text></text>).ClientTemplate("Download file").Title("Download1");
columns.Template(#<text></text>).ClientTemplate("" + Html.ActionLink("<img src='" + Url.Content("~/Content/icons/pdficon_small.png") + "' />", "DocumentDownload2", "Administration", new { id = "#=OrderId#" }, null) + "").Title("Download2");
})
.ToolBar(toolbar => toolbar.Save().Text("Save Changes"))
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Selectable()
.Pageable(paging => paging
.Input(false)
.Numeric(true)
.PreviousNext(true)
.PageSizes(new int[] { 5, 10, 25, 50 })
.Refresh(false)
)
.DataSource(dataSource => dataSource
.Ajax()//bind with Ajax instead server bind
.PageSize(10)
.ServerOperation(true)
.Model(model =>
{
model.Id(p => p.OrderId);
})
.Read(read => read.Action("GetOrder", "Administration").Type(HttpVerbs.Get))
.Update("EditOrder", "Administration")
)
)
**controller**
public ActionResult Download1()
{
string contentType = "application/pdf";
string filePath = Server.MapPath("~/Files/OrderDetails.pdf");
return File(filePath, contentType, "OrderDetails.pdf");
}
public ActionResult Download2(int orderId)
{
string contentType = "application/xlsx";
string filePath = Server.MapPath("~/Files/OrderDetails.pdf");
return File(filePath, contentType, "OrderDetails.pdf_" + orderId.ToString() + ".xlsx");
}

You can't implement the PDF download on the client-side easily. You should instead stream the PDF file using another action method. You can check this question for some ideas: Retrieve and display image from database using ASP.Net MVC
The grid should contain a link to this action method:
.ClientTemplate("<a href='/administration/getpdf?orderid=#= OrderID #'>get pdf</a>");
public ActionResult GetPdf(int orderID)
{
// find the pdf by orderid
return File(stream, "application/pdf", "DownloadName.pdf");
}

You'd have to implement this yourself. KendoUI is a client-side technology, and has nothing to do with serving an arbitary PDF from a datasource.
If you'd like to generate a PDF, look up the following resources:
PDF:
http://www.kendoui.com/code-library/mvc/grid/export-grid-to-pdf.aspx
Maybe this UserVoice entry:
http://feedback.kendoui.com/forums/127393-kendo-ui-feedback/suggestions/3494585-kendoui-mvc-serverside-wrappers-should-allow-expor

The available answers seem to be outdated. There are new developments in this area. Please check this example and also telerik api reference . Hope it helps in the future.

Another way to do the same thing, with ActionLink inside the ClientTemplate:
columns.Template(#<text>
#Html.ActionLink("get pdf", "getpdf", "administration", new { orderid= #item.OrderId}, null)
</text>);
As taken from: http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/faq#how-do-i-use-action-links

Related

A Kendo Template With DropDownList inside Form Louyot Genrate Ivald Template when setting ServerFiltering to True

When creating kendo ui Javascript template and using a form layout, adding a DropDownList with server filtering set to true , kendo ui will throw an "invalid template " error.
While setting the server filtering to false it will work as expected
Sample code
https://github.com/Elrashid/TelerikAspNetCoreApp.tiket.2022121901
compiled code
https://github.com/Elrashid/TelerikAspNetCoreApp.tiket.2022121901/releases/download/202211219194020/publish-self-contaned.zip
Tested Scenarios:
✔DropDownList with ServerFiltering trueinside Kendo Tempate will work
✔DropDownList with ServerFiltering false will was a Form Layout Editer inside Kendo Tempate will work
❌DropDownList with ServerFiltering true will was a Form Layout Editer inside Kendo Tempate will not work
Error :
[](https://i.stac> k.imgur.com/nULHE.png)
Error Code :
#(Html.Kendo().Form()
.Name("Biblio_Form")
.HtmlAttributes(new { action = "Biblio_Save", method = "POST", })
.Layout("grid")
.Grid(g => g.Cols(1).Gutter(10))
.Validatable(v =>
{
v.ValidateOnBlur(true);
v.ValidationSummary(vs => vs.Enable(false));
})
.Items(items =>
{
items.Add()
.Field(f => f.BiblioId)
.Label(l => l.Text("Biblio Id"))
.Editor(e =>
{
e.DropDownList()
.HtmlAttributes(new { })
.DataTextField("Title")
.DataValueField("BiblioId")
.NoDataTemplate("nodata")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("biblio_read", "Home");
})
.ServerFiltering(true);
});
});
}).ToClientTemplate())
Explicitly call the .ToClientTemplate() configuration method.
Addunique identifier thru .Name() configuration option.
this will have to be doen even if you call.ToClientTemplate() on the parent , so you have to call it for the children also
<script type="text/x-kendo-template" id="...........">
#(Html.Kendo().Form<Biblio>()
.Name("Biblio_Form")
....
.Items(items =>
{
items.Add()
.Field(f => f.BiblioId)
.Label(l => l.Text("Biblio Id"))
.Editor(e =>
{
e.DropDownList()
.Name("serverFilteringTrue")
.DataTextField("Title")
.DataValueField("BiblioId")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("biblio_read", "Home");
})
.ServerFiltering(true);
}).ToClientTemplate();
});
}).ToClientTemplate())
</script>
Ref.
[ASP.NET Core Data Grid Component Client Detail Templates - Telerik UI for ASP.NET Core]
(https://docs.telerik.com/aspnet-core/html-helpers/data-management/grid/templates/client-detail-template)

asp.net MVC autocomplete with Html.TextBoxFor

I am modifying a preexisting application. I am trying to add the jquery autocomplete functionality. I have it working and calling the controller but the problem is the name attribute in the input field is "someClass.someMethod" so because I can't put this in the controller parameter like this, but still want to satisfy asp.net's Model Binding rules, what can I do?
Controller:
public JsonResult GetPs(string pN, PSModel pS)
{
List<string> pNs = null;
pNs= pS.PEntryBL.BusinessLayerPS.PS
.Where(x => x.Text.StartsWith(pN)).Select(y => y.Text).ToList();
return Json(pNs, JsonRequestBehavior.AllowGet);
}
View:
$(function () {
$("#autoCompletePNBox").autocomplete({
source: '#Url.Action("GetPs", "PS", new {pS = #Model})'
});
});
In Form:
#Html.Label("Scan PN: ", new { #class = "DFont"})
#Html.TextBoxFor(r => r.PEntryBL.PS, new { #class = "pageFont", id = "autoCompletePNBox" })
Using This Post
I was able to get it working by grabbing the value of the input field and passing it on each function call (or each time a user enters a character).
Now when the user selects the item from the autocomplete list, and selects submit then the frameworks form model binding behind the scenes will still work as originally implemented.
Here is the jquery code change:
<script type="text/javascript">
$(function () {
var src = '#Url.Action("GetPs", "PS", new {pS = #Model})'
$("#autoCompletePNBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
pN: $("#autoCompletePNBox").val()
},
success: function (data) {
response(data);
}
});
}
});
});
I couldn't figure this out right away as my Jquery skills are not very strong. Hopefully this helps someone.

ASP.NET MVC4 View Model Parameter Null when Posted

I want to use a view model as input to an Edit form. Call it -
public class StudentEditViewModel
{
}
My Edit action method creates the object and passes it to the Edit view, which has #model set to StudentEditViewModel. This works fine - all data is displayed as expected.
BUT, when I post the changes (using ) things fall apart. Here is the skeleton of my action handler:
[HttpPost]
public ActionResult Edit(StudentEditViewModel student)
{
}
The problem is that "student" is null. All the online examples appear to do it this way, but I'm obviously missing something. Can anyone help me out?
I'll be happy to provide more details if necessary. Thanks in advance.
Your StudentEditViewModel needs properties (E.g public string name { get; set;}) because the StudentEditViewModel should have a property basis for it to have a value and in your view, use the basic LINQ syntax
using(Html.BeginForm())
{
#html.TextBoxFor(u => u.name)
<input type="submit"/>
}
Try adding also with a non-Data annotation ActionResult and check out the breakpoints. This was my mistake before when I tried to program. Hope I can help you.
Are you using Explicitly typed View Model? In this case you can do it by jquery as follows:
$("#btnSave").click(function (event) {
event.preventDefault();
if ($("#form1").valid()) {
var formInput = $('#form1').serializeObject();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: 'your controller action url be here',
data: JSON.stringify(formInput)
})
.done(function (data, textStatus, jqXHR) {
showMsg('page-message', 'success', 'Success!', 'The item was saved.');
$('#PriorityDateId').val(data);
window.location.href = 'after save where you want to redirect(give url)';
})
.fail(function (jqXHR, textStatus, errorThrown) {
showResponse('page-message', 'error', 'Error!', jqXHR.responseText);
});
}
});
If need more info, let me know..
Your model should contain some properties like so:
model:
public class StudentEditViewModel
{
//Sample Properties
public string Name{get;set;}
public int Age {get;set;}
}
And your view should look something like this.
#model Nameofyourproject.Model.StudentEditViewModel
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name) // this where you will enter a value for the Name property
#Html.LabelFor(m => m.Age)
#Html.TextBoxFor(m => m.Age) // this where you will enter a value for the Age property
<input type="submit"/> //this will submit the values to your action method.
}
you will be able to get this values now in your action method
[HttpPost]
public ActionResult Edit(StudentEditViewModel student)
{
var name = student.Name;
var age = student.Age;
}

Kendo Grid Custom comboBox Filter

I has grid which will load data as filterable combo box, So I need to create custom filter for this column with filterable combo box also.
I create combo box and assign it to the column filter UI. My problem is when the combobox read the data from the controller it does not send the filter text to the controller.
<script type="text/javascript">
function outletFilter(element) {
debugger;
element.kendoComboBox({
dataTextField: "OutletNameE",
dataValueField: "OutletID",
autoBind: false,
minLength: 1,
dataSource: {
serverFiltering: true,
transport: {
read: "#Url.Action("GetOutletsCombo")"
}
},
optionLabel: "--Select Value--"
});
}
</script>
#(Html.Kendo().Grid<Spine.ERP.ViewModel.AccountReceivableOutletViewModel>()
.Name("ARDetails_OutletGrid")
.Columns(columns =>
{
columns.Bound(p => p.AccountReceivableID).Hidden();
columns.Bound(p => p.AccountReceivableOutletID);
columns.Bound("Outlet.OutletName")
.EditorTemplateName("OutletForeignKeyEditor")
.ClientTemplate("<a>#=OutletID ##=OutletID? '-' : ' ' ##=OutletID ?
Outlet.OutletName : ' ' #</a>")
.Filterable(filter => filter.UI("outletFilter"));
})
And here are my controller function
public ActionResult GetOutletsCombo(string text)
{
if (text == null)
text = "";
var result = new List<OutletViewModel>();
var Outlets = outletRepository.FilterOnID("Outlet", new string[] { "OutletID", "OutletNameE" }, text).ToList();
result = (from outlet in Outlets
select new OutletViewModel
{
OutletID = outlet.OutletID,
OutletNameE = outlet.OutletNameE,
OutletNameA = outlet.OutletNameA
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
First of all if you perform a "read", it does not send any additional value to the controller so in "public ActionResult GetOutletsCombo(string text)" you wouldn't get any value in "text".
For server filtering you can see kendo's demo on the following page
http://demos.kendoui.com/web/combobox/serverfiltering.html
As far as I get from your question, you want to do a Kendo Grid and on there you want to have a combobox to filter the data in the grid. In this case, you may check the similar kind of demo in Kendo's site
http://demos.kendoui.com/web/grid/toolbar-template.html
For filter menu you can check this on kendo under ASP.NET MVC
http://demos.kendoui.com/web/grid/filter-menu-customization.html
Hope you can work out your problem from these examples. In case you can't then put a comment underneath this post. I shall try again to help you.

MvcContrib grid conditional cell formatting based on model value

I need to conditional formatting a cell value based on a boolean value in the model.
I have the column col.For(item => item.Detail);
If item.Unfinished I need to apply some css style
How can I do that?
The answer is in my comment to the original post:
http://groups.google.com/group/mvccontrib-discuss/browse_thread/thread/f872d298cc9d53dc
column.For(x => x.Surname).Attributes(x => {
if(x.Item.Surname == "foo") {
return new Dictionary<string, object> { { "style", "color:red"} };
}
return new Dictionary<string, object>();
});
if you still looking for solution:
"
The above property of the MVCContrib grid also does the trick.
<%= Html.Grid(Model.Services).AutoGenerateColumns()
.Columns(column => {
column.For(a => Html.ActionLink("Editar", "Edit", new { id = a.Id }))
.InsertAt(0).Encode(false)
.CellCondition(x =>
(x.CreatedBy==Membership.GetUser().UserName));
})
.Sort(Model.GridSortOptions)
.Attributes(#class => "table-list")
.Empty(Resources.NO_DATA_TO_DISPLAY)
%>
"
Credits to Jeremy Skinner
http://www.jeremyskinner.co.uk/2010/04/27/mvccontrib-grid-part-7-auto-generated-columns/comment-page-1/#comment-19059
and jpassos who originally posted it here:
http://forums.asp.net/p/1559843/3850767.aspx