Telerik Forums
UI for ASP.NET MVC Forum
1 answer
68 views

So I need to see just the events with a specific Title, ID or Employee . . . . .

I searched and I found this way to implement the filter in the razor code on the scheduler directly .... but it will show me the filtered events all the time.

So I need to do this dynamically ... with Multi-Select Options...

This is my MultiSelect :

 

@(Html.Kendo().MultiSelect()
                 .Name("events_MultiSelect")
                 .Placeholder("Filter . . .")
                 .ValuePrimitive(true)
                 .DataTextField("Title")
                 .DataValueField("Title")
                 .Events(eventt =>{
                        eventt.Open("openMultiSelect");
                        eventt.Change("changeMultiSelect"); })
                  .DataSource(source =>{
                         source.Custom()
                             .Type("aspnetmvc-ajax")
                             .Transport(transport =>{
                                    transport.Read("GetEvents", "Filter"); })
                                                .Schema(schema =>{
                                                 schema.Data("Data")
                                                    .Total("Total")
                                                    .Errors("Errors");
                                            });
                                        })
                                        )
Ianko
Telerik team
 answered on 05 Mar 2020
8 answers
2.9K+ views

Hey,

So i have a very simple form 2 controls on it,

1 DropdownList

1 DropDownTree

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        @Html.Kendo().DropDownListFor(a => a.BranchId).OptionLabel("Select Branch").DataTextField("Text").DataValueField("Value").BindTo(Model.BranchList).HtmlAttributes(new { @class = "ff_required ff_control", @required = "required" })
    </div>
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <label class="ff_label">Select a parent category (optional)  <span class="ParentCategoryTip"><img src="~/Images/icons/help.png" /></span></label>
    </div>
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
 
    @(Html.Kendo().DropDownTreeFor(a => a.ParentCategoryId)
                                        .DataTextField("Name")
                                        .DataValueField("id")
                                        .Placeholder("Select Category")
                                        .HtmlAttributes(new { style = "width: 100%" })
                                            .Events(events => events
                                            .Change("DropdownTreeChange"))
    )

 

By default when the page loads i do not want to DropdownTree to bind to anything, it must be blank. Only once a selection is made from the BranchId DropDownList then i want the DropDownTree to be populated by passing the BranchId to the action method.

Here is what i have so far

$("#BranchId").on("change", function () {
 
        var tree = $("#ParentCategoryId").data("kendoDropDownTree");
        var val = tree.value();
 
 
        tree.refresh({
            url: "/Setting/GetCategorylist",
            data: {
                Id: val,
                BranchId: $("#BranchId").val()
            }
        });
    });

 

[HttpGet]
       //public async Task<ActionResult> GetCategorylist([DataSourceRequest] DataSourceRequest request, int BranchId)
       public async Task<ActionResult> GetCategorylist(int? Id, int BranchId)
       {
           var Result = await new _GetCategoryTreeList(new FF_ErrorLogger()).GetIdAsync(null,BranchId);
           return Json(Result, JsonRequestBehavior.AllowGet);
       }

 

i cannot get the DropDownTree to rebind its data.

 

Dimitar
Telerik team
 answered on 04 Mar 2020
8 answers
1.7K+ views

Hi

 

I am struggling to get a foreign key to display it's name in Kendo Grid. In my normal MVC views the name displays just fine.

I am using a code first approach in MVC with DBContext instead of using EDMX models.

 

Could someone please help me with this issue.

Help would be appreciated :)

 

Here is the Kendo Grid code for my view:

@(Html.Kendo().Grid<ZerothApp.Models.ProvinceViewModel>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ProvinceName).Filterable(ftb => ftb.Multi(true).Search(true));
        columns.Bound(p => p.Country).Filterable(ftb => ftb.Multi(true).Search(true));
        columns.Bound(p => p.CreatedBy);
        columns.Bound(p => p.DateCreated);
        columns.Bound(p => p.LastEditedBy);
        columns.Bound(p => p.DateLastEdited);
        columns.Template(@<text></text>).ClientTemplate("<a class='editProvince' href='" + Url.Action("Edit", "Province") + "/#=ProvinceIdentifier#'>Edit</a> | <a class='detailsProvince' href='" + Url.Action("Details", "Province") + "/#=ProvinceIdentifier#'>Details</a> | <a class='deleteProvince' href='" + Url.Action("Delete", "Province") + "/#=ProvinceIdentifier#'>Delete</a>").Title("Actions");
    })
    .Pageable()
    .Sortable()
    .Groupable()
    .Scrollable()
    .Filterable()
    .HtmlAttributes(new { style = "height:550px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Sort(sort => sort.Add("ProvinceName").Ascending())
        .PageSize(20)
        .Model(model =>
        {
            model.Id(p => p.ProvinceIdentifier);
            model.Field(p => p.ProvinceIdentifier).Editable(false);
            model.Field(p => p.CountryID).DefaultValue(1);
        })
        .Read(read => read.Action("GetProvinces", "Province"))
    )
                    )

 

Here is the code for my ProvinceViewModel:

public class ProvinceViewModel
    {
        public System.Guid ProvinceIdentifier { get; set; }
 
        public string ProvinceName { get; set; }
 
        public System.Guid CountryID { get; set; }
 
        public string Country { get; set; }
 
        public string CreatedBy { get; set; }
 
        public Nullable<System.DateTime> DateCreated { get; set; }
 
        public string LastEditedBy { get; set; }
 
        public Nullable<System.DateTime> DateLastEdited { get; set; }
 
        public SelectList CountriesSelectList { get; set; }
    }

 

Here is the code for my Province class:

public class Province
    {
        [Key]
        public System.Guid ProvinceIdentifier { get; set; }
 
        public string ProvinceName { get; set; }
 
        public System.Guid CountryID { get; set; }
 
        public string CreatedBy { get; set; }
 
        public Nullable<System.DateTime> DateCreated { get; set; }
 
        public string LastEditedBy { get; set; }
 
        public Nullable<System.DateTime> DateLastEdited { get; set; }
 
    }

 

Here is the code for my ProvinceController:

using System;
using ZerothApp.Models;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity.Owin;
using DataTables.Mvc;
using System.Collections.Generic;
using System.Net;
using System.Data.Entity;
using System.Threading.Tasks;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
 
 
namespace ZerothApp.Controllers
{
    public class ProvinceController : Controller
    {
        private ApplicationDbContext _dbContext;
 
        public ApplicationDbContext DbContext
        {
            get
            {
                return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            }
            private set
            {
                _dbContext = value;
            }
 
        }
 
        public ProvinceController()
        {
 
        }
 
        public ProvinceController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
 
        // GET: Province
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult GetProvinces([DataSourceRequest] DataSourceRequest request)
        {
            return Json(GetProvinceViewModels().ToDataSourceResult(request));
        }
 
        private IQueryable<ProvinceViewModel> GetProvinceViewModels()
        {
            return DbContext.Provinces
                            .Select(
                            c => new ProvinceViewModel
                            {
                                ProvinceIdentifier = c.ProvinceIdentifier,
                                ProvinceName = c.ProvinceName,
                                CountryID = c.CountryID,
                                CreatedBy = c.CreatedBy,
                                DateCreated = c.DateCreated,
                                LastEditedBy = c.LastEditedBy,
                                DateLastEdited = c.DateLastEdited
                            });
        }
 
 
        // GET: Province/Create
        public ActionResult Create()
        {
            var model = new ProvinceViewModel();
            model.CountriesSelectList = GetCountriesSelectList();
            return View("Add", model);
        }
 
        // POST: Province/Create
        [HttpPost]
        public async Task<ActionResult> Create(ProvinceViewModel provinceVM)
        {
 
            provinceVM.CountriesSelectList = GetCountriesSelectList();
 
            if (!ModelState.IsValid)
                return View("Add", provinceVM);
 
            Province province = MaptoModel(provinceVM);
 
            DbContext.Provinces.Add(province);
            var task = DbContext.SaveChangesAsync();
            await task;
 
            if (task.Exception != null)
            {
                ModelState.AddModelError("", "Unable to add the Asset");
                return View("Add", provinceVM);
            }
 
            return RedirectToAction("Index");
        }
 
        // GET: Province/Edit/5
        public ActionResult Edit(Guid id)
        {
            var province = DbContext.Provinces.FirstOrDefault(x => x.ProvinceIdentifier == id);
 
            ProvinceViewModel provinceViewModel = MapToViewModel(province);
 
            if (Request.IsAjaxRequest())
                return PartialView("Edit", provinceViewModel);
            return View(provinceViewModel);
        }
 
        // POST: Province/Edit/5
        [HttpPost]
        public async Task<ActionResult> Edit(ProvinceViewModel provinceVM)
        {
 
            provinceVM.CountriesSelectList = GetCountriesSelectList(provinceVM.CountryID);
 
            if (!ModelState.IsValid)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return View(Request.IsAjaxRequest() ? "Edit" : "Edit", provinceVM);
            }
 
            Province province = MaptoModel(provinceVM);
 
            DbContext.Provinces.Attach(province);
            DbContext.Entry(province).State = EntityState.Modified;
            var task = DbContext.SaveChangesAsync();
            await task;
 
            if (task.Exception != null)
            {
                ModelState.AddModelError("", "Unable to update the Asset");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return View(Request.IsAjaxRequest() ? "Edit" : "Edit", provinceVM);
            }
 
            return RedirectToAction("Index");
 
        }
 
        public async Task<ActionResult> Details(Guid id)
        {
            var province = await DbContext.Provinces.FirstOrDefaultAsync(x => x.ProvinceIdentifier == id);
            var provinceVM = MapToViewModel(province);
 
            if (Request.IsAjaxRequest())
                return PartialView("Details", provinceVM);
 
            return View(provinceVM);
        }
 
        // GET: Province/Delete/5
        public ActionResult Delete(Guid id)
        {
            var province = DbContext.Provinces.FirstOrDefault(x => x.ProvinceIdentifier == id);
 
            ProvinceViewModel provinceViewModel = MapToViewModel(province);
 
            if (Request.IsAjaxRequest())
                return PartialView("Delete", provinceViewModel);
            return View(provinceViewModel);
        }
 
        // POST: Province/Delete/5
        [HttpPost, ActionName("Delete")]
        public async Task<ActionResult> DeleteProvince(Guid ProvinceIdentifier)
        {
            var province = new Province { ProvinceIdentifier = ProvinceIdentifier };
            DbContext.Provinces.Attach(province);
            DbContext.Provinces.Remove(province);
 
            var task = DbContext.SaveChangesAsync();
            await task;
 
            if (task.Exception != null)
            {
                ModelState.AddModelError("", "Unable to Delete the Province");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                ProvinceViewModel provinceVM = MapToViewModel(province);
                return View(Request.IsAjaxRequest() ? "Delete" : "Delete", provinceVM);
            }
 
            return RedirectToAction("Index");
 
        }
 
        private SelectList GetCountriesSelectList(object selectedValue = null)
        {
            return new SelectList(DbContext.Countries
                                            .Select(x => new { x.CountryIdentifier, x.CountryName }),
                                                "CountryIdentifier",
                                                "CountryName", selectedValue);
        }
 
        private ProvinceViewModel MapToViewModel(Province province)
        {
            var country = DbContext.Countries.Where(x => x.CountryIdentifier == province.CountryID).FirstOrDefault();
 
            ProvinceViewModel provinceViewModel = new ProvinceViewModel()
            {
                ProvinceIdentifier = province.ProvinceIdentifier,
                ProvinceName = province.ProvinceName,
                CountryID = province.CountryID,
                CreatedBy = province.CreatedBy,
                DateCreated = province.DateCreated,
                LastEditedBy = province.LastEditedBy,
                DateLastEdited = province.DateLastEdited,
                Country = country != null ? country.CountryName : String.Empty,
                CountriesSelectList = new SelectList(DbContext.Countries
                                                                    .Select(x => new { x.CountryIdentifier, x.CountryName }),
                                                                      "CountryIdentifier",
                                                                      "CountryName", province.CountryID)
            };
 
            return provinceViewModel;
        }
 
        private Province MaptoModel(ProvinceViewModel provinceVM)
        {
            Province province = new Province()
            {
                ProvinceIdentifier = provinceVM.ProvinceIdentifier,
                ProvinceName = provinceVM.ProvinceName,
                CountryID = provinceVM.CountryID,
                CreatedBy = provinceVM.CreatedBy,
                DateCreated = provinceVM.DateCreated,
                LastEditedBy = provinceVM.LastEditedBy,
                DateLastEdited = provinceVM.DateLastEdited
            };
 
            return province;
        }
    }
}

 

Here is the code for my CountryViewModel:

public class CountryViewModel
    {
        [Required]
        public System.Guid CountryIdentifier { get; set; }
 
        public string CountryName { get; set; }
 
        public string CreatedBy { get; set; }
 
        public Nullable<System.DateTime> DateCreated { get; set; }
 
        public string LastEditedBy { get; set; }
 
        public Nullable<System.DateTime> DateLastEdited { get; set; }
    }

 

Here is the code for my Country class:

public class Country
    {
        [Key]
        public System.Guid CountryIdentifier { get; set; }
 
        public string CountryName { get; set; }
 
        public string CreatedBy { get; set; }
 
        public Nullable<System.DateTime> DateCreated { get; set; }
 
        public string LastEditedBy { get; set; }
 
        public Nullable<System.DateTime> DateLastEdited { get; set; }
    }

 

And here is the code for my CountriesController:

 

using System;
using ZerothApp.Models;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity.Owin;
using DataTables.Mvc;
using System.Collections.Generic;
using System.Net;
using System.Data.Entity;
using System.Threading.Tasks;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
 
namespace ZerothApp.Controllers
{
    public class CountryController : Controller
    {
        private ApplicationDbContext _dbContext;
 
        public ApplicationDbContext DbContext
        {
            get
            {
                return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            }
            private set
            {
                _dbContext = value;
            }
 
        }
 
        public CountryController()
        {
 
        }
 
        public CountryController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
 
        // GET: Countries
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult GetCountries([DataSourceRequest] DataSourceRequest request)
        {
            return Json(GetCountryViewModels().ToDataSourceResult(request));
        }
 
        private IQueryable<CountryViewModel> GetCountryViewModels()
        {
            return DbContext.Countries
                            .Select(
                            c => new CountryViewModel
                            {
                                CountryIdentifier = c.CountryIdentifier,
                                CountryName = c.CountryName,
                                CreatedBy = c.CreatedBy,
                                DateCreated = c.DateCreated,
                                LastEditedBy = c.LastEditedBy,
                                DateLastEdited = c.DateLastEdited
                            });
        }
 
 
        // GET: Countries/Create
        public ActionResult Create()
        {
            var model = new CountryViewModel();
            return View("Add", model);
        }
 
        // POST: Countries/Create
        [HttpPost]
        public async Task<ActionResult> Create(CountryViewModel countryVM)
        {
            if (!ModelState.IsValid)
                return View("Add", countryVM);
 
            Country country = MaptoModel(countryVM);
 
            DbContext.Countries.Add(country);
            var task = DbContext.SaveChangesAsync();
            await task;
 
            if (task.Exception != null)
            {
                ModelState.AddModelError("", "Unable to add the country");
                return View("Add", countryVM);
            }
 
            return RedirectToAction("Index");
        }
 
        // GET: Countries/Edit/5
        public ActionResult Edit(Guid id)
        {
            var country = DbContext.Countries.FirstOrDefault(x => x.CountryIdentifier == id);
 
            CountryViewModel countryViewModel = MapToViewModel(country);
 
            if (Request.IsAjaxRequest())
                return PartialView("Edit", countryViewModel);
            return View(countryViewModel);
        }
 
        // POST: Countries/Edit/5
        [HttpPost]
        public async Task<ActionResult> Edit(CountryViewModel countryVM)
        {
            if (!ModelState.IsValid)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return View(Request.IsAjaxRequest() ? "Edit" : "Edit", countryVM);
            }
 
            Country country = MaptoModel(countryVM);
 
            DbContext.Countries.Attach(country);
            DbContext.Entry(country).State = EntityState.Modified;
            var task = DbContext.SaveChangesAsync();
            await task;
 
            if (task.Exception != null)
            {
                ModelState.AddModelError("", "Unable to update the Asset");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return View(Request.IsAjaxRequest() ? "Edit" : "Edit", countryVM);
            }
 
            return RedirectToAction("Index");
 
        }
 
        public async Task<ActionResult> Details(Guid id)
        {
            var country = await DbContext.Countries.FirstOrDefaultAsync(x => x.CountryIdentifier == id);
            var countryVM = MapToViewModel(country);
 
            if (Request.IsAjaxRequest())
                return PartialView("Details", countryVM);
 
            return View(countryVM);
        }
 
        // GET: Countries/Delete/5
        public ActionResult Delete(Guid id)
        {
            var country = DbContext.Countries.FirstOrDefault(x => x.CountryIdentifier == id);
 
            CountryViewModel countryViewModel = MapToViewModel(country);
 
            if (Request.IsAjaxRequest())
                return PartialView("Delete", countryViewModel);
            return View(countryViewModel);
        }
 
        // POST: Countries/Delete/5
        [HttpPost, ActionName("Delete")]
        public async Task<ActionResult> DeleteCountry(Guid CountryIdentifier)
        {
            var country = new Country { CountryIdentifier = CountryIdentifier };
            DbContext.Countries.Attach(country);
            DbContext.Countries.Remove(country);
 
            var task = DbContext.SaveChangesAsync();
            await task;
 
            if (task.Exception != null)
            {
                ModelState.AddModelError("", "Unable to Delete the country");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                CountryViewModel countryVM = MapToViewModel(country);
                return View(Request.IsAjaxRequest() ? "Delete" : "Delete", countryVM);
            }
 
            return RedirectToAction("Index");
 
        }
 
        private CountryViewModel MapToViewModel(Country country)
        {
 
            CountryViewModel countryViewModel = new CountryViewModel()
            {
                CountryIdentifier = country.CountryIdentifier,
                CountryName = country.CountryName,
                CreatedBy = country.CreatedBy,
                DateCreated = country.DateCreated,
                LastEditedBy = country.LastEditedBy,
                DateLastEdited = country.DateLastEdited,
            };
 
            return countryViewModel;
        }
 
        private Country MaptoModel(CountryViewModel countryVM)
        {
            Country country = new Country()
            {
                CountryIdentifier = countryVM.CountryIdentifier,
                CountryName = countryVM.CountryName,
                CreatedBy = countryVM.CreatedBy,
                DateCreated = countryVM.DateCreated,
                LastEditedBy = countryVM.LastEditedBy,
                DateLastEdited = countryVM.DateLastEdited
            };
 
            return country;
        }
    }
}
Alex Hajigeorgieva
Telerik team
 answered on 02 Mar 2020
3 answers
448 views

I am using the tabstrip to create a step-wise type form where each tab has a different model and partial view.

The content of a tab is based on what was entered on a previous tab.

I am using LoadContentFrom to call a controller action to return the partial view and model.

This is working fine.

Problem Scenario:

If the user enters/saves data in tab 2, goes to tab 3 and enters/saves data and then goes back to tab 2 I have a controller action that removes the data saved in tab 3.

When they finish updating data in tab 2 and go to tab 3 the next time I don't want that stale content, I need to be able to call the controller action to return a new partial with a model.

Isn't there a way to say that a tab SHOULD NOT cache the content?

I want fresh content every time they go to the tab...and, of course, any events related to that new partial need to work.

Petar
Telerik team
 answered on 02 Mar 2020
1 answer
141 views

Hi,

Clicking the following menu items causes postback. How do load the page but prevent postback?

 

@(Html.Kendo().Menu()
    .Name("Menu")
    .HtmlAttributes(new { style="width:100%" })
    .Items(items =>
    {
        items.Add().Text("People").Action("Index","Home");
        items.Add().Text("Organization").Action("Organization","Home");
        items.Add().Text("Committees").Action("Committee","Home");
    })
)
Martin
Telerik team
 answered on 28 Feb 2020
3 answers
1.0K+ views

I have a table, that I need to freeze the header.

Is there a option to freeze the header, without set Scrollable?

When I set the Scrollable, the header begin freeze. But, after this, when I group any column, the width of the rows change.

Tsvetomir
Telerik team
 answered on 28 Feb 2020
4 answers
323 views

I have a common auto complete control that I use on two different pages.  The AutoComplete control is populated with the same data set as a Kendo Grid on the page. Both pages have filters by which users can filter the data in the Kendo Grid (using built in Kendo Filter functionality).  We don't want superfluous results to show up in the AutoComplete therefore we reset the AutoComplete dataset to match the newly filtered dataset of the Kendo Grid.  To accomplish this we use the .setDataSource method of the AutoComplete control (see code below).  The AutoComplete control works well within page A after the new data source is set.  However, the AutoComplete does not work within Page B.  When a user types in criteria into the AutoComplete in Page B the popup never shows, not even to say "NO DATA FOUND".  No error is shown within the Browser Developer tools either.  When I interrogate the control I see that the data set is in fact applied correctly.  I see the correct number of items.  In fact after typing in some value to the AutoComplete control on Page B when I interrogate the dataSource I see that the view property of the dataSource is populated with the correct filtered items (i.e. if I type in "asse" into the AutoComplete then I see only two items in the view with "Asset" in their name).  However, the pop up still doesn't show up.  When I interrogate the popup I see nothing in its view.  It seems like the pop up is just lying dead in the water for Page B.  I have tried many things to figure out why.  Does anyone have a suggestion for something to look into?

//prepare Kendo Filters for Kendo Grid
var siteFilters = buildSiteMenuFilters(result.data);
//apply Kendo Filters to Kendo Grid
menuGridDataSource = $("#MenuGrid").data("kendoGrid").dataSource;
menuGridDataSource.filter(siteFilters);
//get filtered dataset from Kendo Grid
var allData = menuGridDataSource.data();
var query = new kendo.data.Query(allData);
//create variable to store filtered results
saveMenu = [];
//convert filtered dataset from Kendo Grid into an array of objects that match the AutoComplete control Instantiation
filteredList = query.filter(siteFilters).data;
filteredListLength = filteredList.length;
for (var i = 0; i < filteredListLength; i++) {
saveMenu.push({ Id: filteredList[i].Id, Name: filteredList[i].Name, LongName: filteredList [i].LongName, uid: filteredList[i].LongName })
}
//set the AutoComplete control data source to match the new filtered list
var menuSearchAutoComplete = $("#menuSearch").data("kendoAutoComplete");
menuSearchAutoComplete.setDataSource(removeHtmlTags(saveMenu));

 

Sally
Top achievements
Rank 1
 answered on 27 Feb 2020
5 answers
643 views
If I just want US English, can I delete the rest of the culture files from my generated Telerik MVC project?
Tsvetomir
Telerik team
 answered on 27 Feb 2020
2 answers
251 views

Hi I would like to develop a user management screen using Telerik grid having one drop down column from which user can able select the role. But when user selecting any role from dropdown its not getting bind in backend. Please find attached code below.

 

Role.cshtml (Its under ..\Views\Shared\EditorTemplates)

@model IT_GRCData_Service.ViewModel.RoleOptionViewModel 

@(Html.Kendo().DropDownList().Name("roleOption")
            .DataTextField("PortalRoleName")
            .DataValueField("PortalRoleId")
            .DataSource(d => d
                .Read(r => r.Action("Index", "Role"))
            )
            .ValuePrimitive(true)
            .AutoBind(true)
)

RoleControler.cs

 public class RoleController : Controller
    {
        private GRCPortalEntities db = new GRCPortalEntities();
        public JsonResult Index()
        {
            
            var roleOption = db.PORTAL_ROLE.Select(s => new RoleOptionViewModel
            {               
                PortalRoleId = s.PORTAL_ROLE_ID,
                PortalId = s.PORTAL_ID,
                PortalRoleName = s.PORTAL_ROLE_NAME,
                PortalRoleDescription = s.PORTAL_ROLE_DESCRIPTION,
                IsActive = s.IS_ACTIVE
            });

            roleOption = roleOption.Where(r => r.IsActive);
            return this.Json(roleOption, JsonRequestBehavior.AllowGet);
        }
    }

RoleOptionViewModel.cs

public class RoleOptionViewModel
    {
        public int PortalRoleId { get; set; }
        public int PortalId { get; set; }
        public string PortalRoleName { get; set; }
        public string PortalRoleDescription { get; set; }
        public bool IsActive { get; set; }
    }

Above are used for dropdown template..

Below are used for grid design..

UseManagementViewModel.cs

 public class UserManagementViewModel
    {
        public string Guid { get; set; }
        public string UserName { get; set; }
        public string PwCPreferredEmail { get; set; }
        public int PortalUserId { get; set; }
        public bool IsActive { get; set; }

        [UIHint("Role")]
        public RoleOptionViewModel RoleOptionViewModelProperty { get; set; }

    }

UserManagement\Index.cshtml

@using IT_GRCData_Service.ViewModel;
@{
    ViewBag.Title = "User Management";
}

<div class="panel panel-danger">
    <div class="panel-heading">
        <div class="panel-title" style="font-size: 14px; ">
            <b style="padding-right:50px">User Management</b>
        </div>
        <div style="float:right; font-size: 85%; position: relative; top:-10px">help?</div>
    </div>
    <div class="panel-body">
        @(Html.Kendo().Grid<UserManagementViewModel>()
                            .Name("gridUserManagement")
                            .Columns(columns =>
                            {
                                columns.Bound(c => c.UserName).Title("User Name");
                                columns.Bound(c => c.PwCPreferredEmail).Title("Preferred Mail");
                                columns.Bound(c => c.Guid).Title("User Guid");
                                columns.Bound(c => c.RoleOptionViewModelProperty).ClientTemplate("#: RoleOptionViewModelProperty.PortalRoleName #").Title("Role");
                                columns.Bound(c => c.IsActive).Title("Is Active").ClientTemplate("<input type='checkbox' #= IsActive ? checked='checked' :'' # />");
                                columns.Command(command => { command.Edit(); command.Destroy(); });
                            })
                            .ToolBar(t => t.Create())
                            .Editable(editable => editable.Mode(GridEditMode.InLine))
                            .Pageable()
                            .Sortable()
                            .Scrollable()
                            .HtmlAttributes(new { style = "height:550px;" })
                            .DataSource(dataSource => dataSource
                                .Ajax()
                                .Events(events => events.Error("error_handler"))
                                .Model(model =>
                                {
                                    model.Id(p => p.PortalUserId);
                                    model.Field(p => p.UserName).Editable(false);
                                    model.Field(p => p.Guid).Editable(false);
                                    model.Field(p => p.PwCPreferredEmail).Editable(false);
                                    //model.Field(p => p.RoleOptionViewModelProperty).Editable(true);
                                    model.Field(p => p.RoleOptionViewModelProperty).DefaultValue(ViewData["roleOption"] as IT_GRCData_Service.ViewModel.RoleOptionViewModel);
                                })
                                .PageSize(20)
                                .Create(update => update.Action("EditingPopup_Create", "Scoring"))
                                .Read(read => read.Action("User_Read", "UserManagement"))
                                .Update(update => update.Action("User_Update", "UserManagement"))
                                .Destroy(update => update.Action("EditingPopup_Destroy", "Scoring"))

                            )
        )
    </div>

      

    <script type="text/javascript">

        function error_handler(e) {
            if (e.errors) {
                var message = "Errors:\n";
                $.each(e.errors, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function () {
                            message += this + "\n";
                        });
                    }
                });
                alert(message);
            }
        }

    </script>

 

UserManagementController .cs

 public class UserManagementController : Controller
    {

        private GRCPortalEntities db = new GRCPortalEntities();
        // GET: UserManagement
        public ActionResult Index()
        {
            ViewData["roleOption"] = db.PORTAL_ROLE.Select(s => new RoleOptionViewModel
            {
                PortalRoleId = s.PORTAL_ROLE_ID,
                PortalId = s.PORTAL_ID,
                PortalRoleName = s.PORTAL_ROLE_NAME,
                PortalRoleDescription = s.PORTAL_ROLE_DESCRIPTION,
                IsActive = s.IS_ACTIVE
            }).First();
            return View();
        }


        public ActionResult Editing_Popup()
        {
            return View();
        }

        public ActionResult User_Read([DataSourceRequest] DataSourceRequest request)
        {
            try
            {
                var userListQuery = db.PORTAL_USER.AsQueryable();
                userListQuery = userListQuery.Where(s => s.PORTAL_USER_ROLE.PORTAL_ROLE_ID > 0);
                var userList = userListQuery.Select(p => new UserManagementViewModel
                {
                    UserName = p.UNIQUE_NAME,
                    Guid = p.USER_GUID,
                    PwCPreferredEmail = p.PWC_PREFERRED_EMAIL,
                    IsActive = p.IS_ACTIVE,
                    PortalUserId = p.PORTAL_USER_ID,
                    RoleOptionViewModelProperty = new RoleOptionViewModel
                    {
                        PortalRoleId = p.PORTAL_USER_ROLE.PORTAL_ROLE.PORTAL_ROLE_ID,
                        PortalId = p.PORTAL_USER_ROLE.PORTAL_ROLE.PORTAL_ID,
                        PortalRoleName = p.PORTAL_USER_ROLE.PORTAL_ROLE.PORTAL_ROLE_NAME,
                        PortalRoleDescription = p.PORTAL_USER_ROLE.PORTAL_ROLE.PORTAL_ROLE_DESCRIPTION,
                        IsActive = p.PORTAL_USER_ROLE.PORTAL_ROLE.IS_ACTIVE
                    }
            });
                var userListResult = userList.ToDataSourceResult(request);
                return Json(userListResult);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult User_Update([DataSourceRequest] DataSourceRequest request, UserManagementViewModel userObj)
        {
            if (userObj != null && ModelState.IsValid)
            {
                userObj.RoleOptionViewModelProperty    //Data not binding with dropdown selection change
    
            }

            return Json(new[] { userObj }.ToDataSourceResult(request, ModelState));

        }

    }

In User_Update dropdown selection change not bunding with old data. Its holding with new data

 

Alex Hajigeorgieva
Telerik team
 answered on 27 Feb 2020
4 answers
396 views

No errors but the chart is not showing.  The model has two "series" that are IEnumerable of objects that have properties for category, value and color.  The model is filled properly and if I don't try to use Ajax via DataSource / action and just load the object and set the Series it works fine.  Meaning I load an object <FlowsInOutChartData> inout in the top of a Razor page and then set the series via .Series(series => ... series.Donut(inout.InFlows) .Name("In Flows") etc. chart works fine.  Want to load via Ajax so the page comes back immediately (the chart takes a few seconds to load due to database calculation delay).

I think the problem is in the series func<>

series.Donut(d => d.InFlows, null)
               .Name("In Flows");

But not sure what I'm doing wrong.

 

@(Html.Kendo().Chart<WAPDBBusiness.Charts.FlowsInOutChartData>()
                                             .Name("chart")
                                             .ChartArea(chartArea => chartArea
                                                 .Background("transparent"))
                                             .Title(title => title
                                                 .Text("Cash Flows")
                                                 .Position(ChartTitlePosition.Bottom)
                                             )
                                             .Legend(legend => legend
                                                 .Visible(false)
                                             )
                                             .SeriesDefaults(series =>
                                                 series.Donut().StartAngle(150)
                                             )
                                              .DataSource(dataSource => dataSource
                                                                .Read(read => read.Action("CashInOutChartData", "PracticeAnalytics")) //Specify the action method and controller names.
                                            )
                                            .Series(series =>
                                                    {
                                                series.Donut(d => d.InFlows, null)
                                                      .Name("In Flows");
                                            })
                                            .Series(series =>
                                                    {
                                                series.Donut(d => d.OutFlows, null)
                                                      .Name("Out Flows");
                                            })
                   )

 

Controller:

public ActionResult CashInOutChartData()
 {
      var data = new WAPDBBusiness.Charts.CashFlowsInOutChart().GetFirmAnalyticsFlowsByQuarter(loginInfo.FirmID, 1, loginInfo.FirmID, true);

 

     return Json(data, JsonRequestBehavior.AllowGet);
 
 }

 

Model:

public class FlowsInOutChartData
    {
        public IEnumerable<FlowInOutChartItem> InFlows { get; set; }
        public IEnumerable<FlowInOutChartItem> OutFlows { get; set; }
    }
    public class FlowInOutChartItem
    {
        public int? myYear { get; set; }
        public int? myQtr { get; set; }
        public decimal Total { get; set; }
        public decimal PercentOfTotal { get; set; }
        /// <summary>
        /// Used by Telerik Donut Chart
        /// </summary>
        public string category
        {
            get
            {
                return "Q" + myQtr.ToString() + " " + myYear.ToString();
            }
        }
        /// <summary>
        /// Used by Telerik Donut Chart
        /// </summary>
        public decimal value
        {
            get
            {
                return PercentOfTotal;
            }
        }
        /// <summary>
        /// Used by Telerik Donut Chart
        /// </summary>
        public string color { get; set; }
      
    }

 

 

Abe
Top achievements
Rank 1
 answered on 27 Feb 2020
Narrow your results
Selected tags
Tags
+? more
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?