Telerik Forums
UI for ASP.NET MVC Forum
4 answers
545 views

I have a grid like this:

@(Html.Kendo().Grid<License>()
      .Name("popupGrid")
      .Columns(columns =>
      {
          columns.Bound(p => p.LicenseId).Width(20).Hidden().HeaderHtmlAttributes(new { @title = "License" });
          columns.ForeignKey(p => p.CustomerId, (System.Collections.IEnumerable)ViewData["customers"], "CustomerID", "CustomerName")
            .Title("Customer").Width(200);
          columns.Bound(p => p.VendorId).Width(20).HeaderHtmlAttributes(new { @title = "Vendor" });
          columns.Bound(p => p.ProductId).Width(20).HeaderHtmlAttributes(new { @title = "Product" });
          columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { @title = "Edit" })).Width(80);
      })
          .ToolBar(toolbar => toolbar.Create().Text("Add").HtmlAttributes(new { @title = "Add" }))
      .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("PopupEditView"))
      .Events(e => e.Edit("onEdit"))
      .DataSource(dataSource => dataSource
          .Ajax()
          .Model(model => model.Id(p => p.LicenseId))
              .Create(create => create.Action("Create", "Home").Type(HttpVerbs.Post))
              .Read(read => read.Action("Read", "Home").Type(HttpVerbs.Post))
              .Update(update => update.Action("Update", "Home").Type(HttpVerbs.Post))
          )
)

and PopupEditView.cshtml :

@(Html.Kendo().DropDownListFor(m => m.CustomerId).Name("CustomerId")
                  .ValuePrimitive(true)
                  .DataTextField("CustomerName")
                  .DataValueField("CustomerId")
               //.OptionLabel("Select Customer...") 
                  .DataSource(dataSource =>
                  {
                      dataSource.Read(read => read.Action("GetCustomers", "Home"))
                                .ServerFiltering(true);
                  })
            )
            @Html.ValidationMessageFor(m => m.CustomerId)

HomeController : 

[HttpPost]
        public JsonResult Create([DataSourceRequest] DataSourceRequest request, License license)
        {
            if (license != null && ModelState.IsValid) // licence.CustomerId is null Model.State is not valid
            {
                LicenseRepository.Repository.Insert(license);
            }
 
            return Json(new[] { license }.ToDataSourceResult(request, ModelState));
        }
 
        public JsonResult GetCustomers()
        {
            return Json(CustomerRepository.Repository.Customers, JsonRequestBehavior.AllowGet);
        }

If .OptionLabel("Select Customer...") is commented  and submit create then licence then CustomerId is null. If user change DropDownList(CustomerId) then it works fine.

Is this a bug? 

 

Nikolay Rusev
Telerik team
 answered on 09 Mar 2016
1 answer
107 views

I'm using the Telerik MVC grid with the .Pdf function. It works fine, but I'd like to format it (page title, page size, etc) but I can't find any documentation regarding it. I followed the steps this this article http://demos.telerik.com/aspnet-mvc/grid/pdf-export and I'd tried to access the documentation referred in this article: http://demos.telerik.com/aspnet-ajax/editor/examples/overview/%5C%27http:/docs.telerik.com/kendo-ui/web/grid/print-export#exporting%5C%27 but the page seems to be down or no longer active.

Can anyone give me any indication on how to achieve this?

Thanks in advance.

Federico.

Milena
Telerik team
 answered on 09 Mar 2016
3 answers
893 views

I have two grids, A and B.

 

After clicking on the save in A,

1. Before passing to the server, I like to automatically calculate values and process some values before sending back to the server.

2. if something wrong a message popup and don't send to the server

3. if everything is good, have a modal popup about sending the data to the server

4. after processing in the server, modal disappear

5. after modal disappear, retrieve the data again from the server for grid B

 

questions:

1. I think I can use ".Events(e => e.Save("onSave"))" as before saving?

2. Any event I should use for after saved?

3. anyway I can pass the data back to the server which is not inside the grid when people click on grid save.

 

thanks!

Vasil
Telerik team
 answered on 09 Mar 2016
5 answers
242 views

I would like to persist the layout of my grid. I save the layout when it changes, - the problem is when to restore it. If I try calling restoreGridLayout in document.ready() the grid hasn't been initialized yet. If I do it in the onNotesGridDataBound-event the data disappears. I've tried calling grid.dataSource.read() manually on a buttonClick after the onNotesGridDataBound-event, which reloads the data, but if I do it in the event in question I end up in an infinite loop reading data.

 

Any ideas?

 

<script>

  function OnNotesGridLayoutChange(e) {        
        var grid = $("#notesGrid").data("kendoGrid");
        var gridStoreName = getGridStoreName("notesGrid");
        var name = gridStoreName + "-grid-options";
        localStorage[name] = kendo.stringify(grid.getOptions());
    }

 

    function OnNotesGridDataBound(e) {
        var gridStoreName = getGridStoreName("notesGrid");
        var grid = $("#notesGrid").data("kendoGrid");

        restoreGridLayout(grid, gridStoreName);

    }

    function restoreGridLayout(grid, gridStoreName) {
        var name = gridStoreName + "-grid-options";
        var options = localStorage[name];
        if (options) {
            grid.setOptions(JSON.parse(options));
        }    
    }

</script>

 

@(Html.Kendo().Grid<WebClient.Models.NoteViewModel>()
        .Name("notesGrid")
        .AutoBind(false)
        .HtmlAttributes(new { style = "height: 1000px;" })
        .Filterable()
        .Scrollable(s => s.Enabled(true))
        .Resizable(r => r.Columns(true))
        .Groupable()
        .Sortable()
        .ColumnMenu()
        .Pageable(pageable => pageable
            .PageSizes(new int[] { 2, 30, 100, 200 })
            .ButtonCount(5)
        )
        .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("SearchForNotes", "Search"))
            .PageSize(20)
            .ServerOperation(false)
        )
        .Events(e => e.ColumnHide("OnNotesGridLayoutChange")
                      .ColumnResize("OnNotesGridLayoutChange")
                      .ColumnShow("OnNotesGridLayoutChange")
                      .ColumnReorder("OnNotesGridLayoutChange")
                       //.DataBinding("onNotesGridDataBinding")
                       .DataBound("OnNotesGridDataBound")
                       .Change("OnNotesGridLayoutChange")
                       .DataBound("OnNotesGridDataBound")
                       )
 
 
       .Selectable(s => s.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
        )

Radoslav
Telerik team
 answered on 09 Mar 2016
1 answer
160 views

Hello,

the feature is to send mail as an attachment with an excel grid file. My question is how I can generate the excel file without clicking "Export Excel". ?

.ToolBar(tools => tools.Custom().Text(@Html.GetStringResource(Constantes.SendMail)).HtmlAttributes(new { id = "sendMail" }))
.ToolBar(tools => tools.Excel())
.Excel(excel => excel
.FileName(Model.ExportExcelFileName + ".xlsx")
.ForceProxy(true)
.Filterable(true)
.AllPages(true)
.ProxyURL(Url.Action("ExcelSave", "Vol"))
)

 

See PJ.

Thank you.

 

Dimitar
Telerik team
 answered on 08 Mar 2016
3 answers
1.4K+ views

Hi,
I have a sample ASP.NET 5 (MVC) web app from Microsoft working in VS2015:

http://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html
I am in attempt to popluate the Telerik Grid with the Model that I have generated above, however having no luck.
Snip from the app:

BooksController:

// GET: Books
public IActionResult Index()
{
    var applicationDbContext = _context.Book;
    return View(applicationDbContext.ToList());
}

Views/Books/Index.chtml:
@(Html.Kendo().Grid(Model)
    .Name("datagrid")
    .Columns(columns =>
    {
        columns.Bound(b=>b.Title);
 
    })
    .DataSource(dataSource => dataSource
        .Ajax()
    )
)

When I debug, Grid does not appear on the page. However, I can see the actual data written in the html source of the page:
HTML:

<div id="datagrid" name="datagrid"></div><script>jQuery(function(){jQuery("#datagrid").kendoGrid({"columns":[{"title":"Title","field":"Title",
 :
"data":{"Data":[{"BookID":2,"AuthorID":null,"Genre":"Gothic parody333","Price":12.95,"Title":"Northanger Abbey","Year":1817,"Author":null},{"BookID":3,"AuthorID":2,"Genre":"Bildungsroman","Price":15.00,"Title":"David Copperfield","Year":1850,"Author":null},{"BookID":4,"AuthorID":3,"Genre":"Picaresque","Price":8.95,"Title":"Don Quixote","Year":1617,"Author":null}],"Total":3}}});});</script>

Would help if you could point out what I may have missed, thanks!

yagimay
Top achievements
Rank 1
 answered on 08 Mar 2016
2 answers
242 views

We are using the multiselect control with values pre-selection and ToDataSourceResult instance as describe in documentation.

Unfortunately, when we post our model and its ModelState is invalid, we return to the view and the control fails to display the pre-selection and the search also stop working.

Here is some sample snippet.

Model

public class CreateModel
{
    [Required]
    public string Name { get; set; }
 
    public List<int> ProductIds { get; set; }
    public List<Product> InitialProducts { get; set; }
}
 
public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
}

Controller

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Create()
    {
        var initialProduct = GetProductList().First();
 
        var model = new CreateModel
        {
            InitialProducts = new List<Product>(new[] { initialProduct }),
            ProductIds = new List<int>(new[] { initialProduct.ProductId })
        };
 
        return View(model);
    }
 
    [HttpPost]
    public ActionResult Create(CreateModel model)
    {
        if (ModelState.IsValid)
            return RedirectToAction("Success");
 
        model.InitialProducts = GetProductList().Where(p => model.ProductIds.Contains(p.ProductId)).ToList();
 
        return View(model);
    }
 
    [HttpGet]
    public ActionResult Success()
    {
        return View();
    }
 
    private static IEnumerable<Product> GetProductList()
    {
        return new[]
        {
            new Product { ProductId = 1, ProductName = "Chai" },
            new Product { ProductId = 2, ProductName = "Chang" },
            new Product { ProductId = 3, ProductName = "Book" },
            new Product { ProductId = 4, ProductName = "Fork" },
            new Product { ProductId = 5, ProductName = "Knife" },
            new Product { ProductId = 6, ProductName = "Spoon" },
            new Product { ProductId = 7, ProductName = "Dish" },
            new Product { ProductId = 8, ProductName = "Glass" },
            new Product { ProductId = 9, ProductName = "Cup" }
        };
    }
     
    [HttpPost]
    public JsonResult GetDataSourceProducts([DataSourceRequest] DataSourceRequest request)
    {
        var products = GetProductList();
 
        if (request.Filters != null && request.Filters.Count > 0)
        {
            var filter = (FilterDescriptor)request.Filters[0];
            products = products.Where(p => p.ProductName.ToLower().Contains((string)filter.Value)).AsEnumerable();
        }
 
        return Json(products.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
    }
}

View

@using (Html.BeginForm("Create", "Home"))
{
    <div>
        @Html.Kendo().TextBoxFor(m => m.Name)
        @Html.ValidationMessageFor(m => m.Name)
    </div>
 
    <div>
        @(Html.Kendo().MultiSelectFor(m => m.ProductIds)
              .DataTextField("ProductName")
              .DataValueField("ProductId")
              .Placeholder("Select products...")
              .AutoBind(false)
              .DataSource(source => source
                  .Custom()
                  .ServerFiltering(true)
                  .Type("aspnetmvc-ajax")
                  .Transport(transport => transport.Read(read => read.Action("GetDataSourceProducts", "Home")))
                  .Schema(schema => schema.Data("Data").Total("Total"))
              )
              .Filter(FilterType.Contains)
              .Value(Model.InitialProducts)
              )
    </div>
 
    <div>
        <button id="Save" type="submit">Save</button>
    </div>
}

 

Is there any kind of work around for this?

Sebastien Veilleux
Top achievements
Rank 1
 answered on 07 Mar 2016
1 answer
265 views

My Model looks Like this:

public class ForecastChartViewModel
{
public int ID { get; set; }
public String PeriodName { get; set; }
public String EstimateDesc { get; set; }
public Decimal EstimateValue { get; set; }
public String ChartColor { get; set; }
public Boolean IsBenchmark { get; set; }

}

I want the periodName to be the values across the X-Axis and each EstimateDesc to be stack on top of each other for that period if IsBenchmark is false, if IsBenchmark is true I'd like to use a line instead of a stack.  EstimateValue is the charted Value.  I want to be able to set the color for the series to the value of the ChartColor as well.

@(Html.Kendo().Chart<ManpowerForecast.Web.ViewModels.ForecastChartViewModel>()
.Name("chart")
.Legend(legend => legend
.Visible(true)
)
.DataSource(ds => ds
.Read(read => read.Action("ReadManpowerReportForecast", "Manpower"))
.Group(group => group.Add(model => model.EstimateDesc))
.Sort(sort => sort.Add(model => model.PeriodName))
)
.SeriesDefaults(seriesDefaults =>
seriesDefaults.Bar().Stack(true)
)
.Series(series =>
{
series
.Column(model => model.EstimateValue)
.Name("#= group.value #")
.Visible(true);
})
.CategoryAxis(axis => axis
.Categories(model => model.PeriodName)
.MajorGridLines(lines => lines.Visible(false))
.Line(line => line.Visible(false))
)
.ValueAxis(axis => axis.Numeric()
.Max(60)
.MajorGridLines(lines => lines.Visible(false))
.Visible(false)
)
)

 

In my Controller "ReadManpowerReportForecast"  I'm just throwing in some junk data for right now to make sure I can get this chart to function before I go through the complexity of forcing my data into the model in this format.  so I could change my model if need be.  The code to load the viewmodel looks liket this:

IList<ForecastChartViewModel> vCharts = new List<ForecastChartViewModel>();
ForecastChartViewModel vChart = new ForecastChartViewModel()
{
PeriodName = "Period1",
EstimateDesc = "Project1",
EstimateValue = 20,
IsBenchmark = false,
ChartColor = "#cc00cc"
};
vCharts.Add(vChart);
vChart = new ForecastChartViewModel()
{
PeriodName = "Period1",
EstimateDesc = "Project2",
EstimateValue = 20,
IsBenchmark = false,
ChartColor = "#aa0033"
};
vCharts.Add(vChart);
vChart = new ForecastChartViewModel()
{
PeriodName = "Period1",
EstimateDesc = "Project3",
EstimateValue = 10,
IsBenchmark = true,
ChartColor = "#110011"
};
vCharts.Add(vChart);
vChart = new ForecastChartViewModel()
{
PeriodName = "Period2",
EstimateDesc = "Project1",
EstimateValue = 30,
IsBenchmark = false,
ChartColor = "#cc00cc"
};
vCharts.Add(vChart);
vChart = new ForecastChartViewModel()
{
PeriodName = "Period2",
EstimateDesc = "Project2",
EstimateValue = 12,
IsBenchmark = false,
ChartColor = "#aa0033"
};
vCharts.Add(vChart);
vChart = new ForecastChartViewModel()
{
PeriodName = "Period2",
EstimateDesc = "Project3",
EstimateValue = 5,
IsBenchmark = true,
ChartColor = "#110011"
};
vCharts.Add(vChart);

T. Tsonev
Telerik team
 answered on 07 Mar 2016
2 answers
125 views

For example, if I have a change event as below

function sliderChange(e)
    {
        var msg = "View is changed to " + e.value;
        $("#e.ID").html(msg);
    }

How can I get slider ID then I can change some control related to this ID? 

Thanks

Tong
Top achievements
Rank 1
 answered on 07 Mar 2016
1 answer
309 views

I have two grids, A and B, in one page. After modifying data on A grid, I like to trigger changes in B grid and save it to the server. Is there method I can call through JavaScript to save grid B?

 

thanks

Vasil
Telerik team
 answered on 07 Mar 2016
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
Upload
ComboBox
MultiSelect
Window
ListView
TabStrip
Menu
Installer and VS Extensions
Spreadsheet
AutoComplete
TreeList
Gantt
PanelBar
NumericTextBox
Filter
ToolTip
Map
Diagram
Button
PivotGrid
Form
ListBox
Splitter
Application
FileManager
Sortable
Calendar
View
MaskedTextBox
PDFViewer
TextBox
Toolbar
MultiColumnComboBox
Dialog
DropDownTree
Checkbox
Slider
Switch
Notification
ListView (Mobile)
Pager
Accessibility
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
MediaPlayer
TileLayout
DateInput
Drawer
SplitView
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Template
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Rating
ScrollView
ButtonGroup
CheckBoxGroup
Licensing
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Localization
MultiViewCalendar
PopOver (Mobile)
Ripple
ScrollView (Mobile)
Switch (Mobile)
PivotGridV2
FlatColorPicker
ColorPalette
DropDownButton
AIPrompt
PropertyGrid
AICodingAssistant
ActionSheet (Mobile)
BulletGraph
Button (Mobile)
Collapsible
Loader
CircularGauge
SkeletonContainer
Popover
HeatMap
Avatar
ColorGradient
CircularProgressBar
SplitButton
StackLayout
TimeDurationPicker
Chip
ChipList
DockManager
ToggleButton
Sankey
OTPInput
ChartWizard
SpeechToTextButton
InlineAIPrompt
TimePicker
StockChart
RadialGauge
ContextMenu
ArcGauge
+? more
Top users last month
Rob
Top achievements
Rank 3
Bronze
Iron
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Bronze
Iron
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?