Telerik Forums
UI for ASP.NET MVC Forum
1 answer
2.8K+ views

Hi,

I have two controls(datepicker and dropdown) outside of the Kendo Grid, I want to send the selected values of those two controls to the controller along with the Grid values on click of save changes of the Kendo Grid.

Could you please help me how to pass those values along with Create or Update Action of Kendo Grid, or If I can bind those values creating hidden columns in the grid, as these values would be required in all the rows while updating.

Below is my view : 

@{
    ViewBag.Title = Project.Web_v5.Framework.PageTitleHelper.GetPageTitle("PigPriceEdit", Request.Url.AbsolutePath);
    Layout = "~/Views/Shared/_Layout_v2.cshtml";
    var sess = new aplCustomerPortal.SessionManagement();
}
<style>

    #grid .k-grid-header, .k-grid-header .k-header {
        color: palevioletred;
        font-size: large;
    }

    #inputvaluesbox {
        height: 25px;
        width:70%;
        margin:0;
    }
    .k-edit-cell input {
        width: 100%;
    }
</style>
@section Scripts
{
    <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);
            }
        }

        function showEdit(e) {
            e.preventDefault();
            var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
            window.location.href = '@Url.Action("PigPriceEdit", "MarketingPigPrice")' + '?pModelId=' + dataItem.id + '&pContactId=@ViewBag.ContactId';
        }

        $(function () {
            kendo.culture("en-AU");
        });

          $("#bEdit").click(function () {
                window.location.href = '@Url.Action("PigPriceEdit", "MarketingPigPrice")'  + '&pContactId=@ViewBag.ContactId';
            });

       
    </script>
}

<div class="col-md-12">
    <form>

        <div class="form-group col-md-12">
            <br />
            <h3 class="panel-title">
                Form Type : Buyer
            </h3>
        </div>
        <div class="col-md-12">
            <div>
                <table>
                    <tr>
                        <td>
                            <h3>
                                Week End Date&nbsp;
                                @(Html.Kendo().DatePicker().Name("datepicker").Format("dd/MM/yyyy").DisableDates(DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Saturday).HtmlAttributes(new { required = "required", validationmessage = "Week End is required", style = "width:100%;", placeholder = "dd/MM/yyyy" })
                                <br />
                            </h3>
                        </td>
                        <td>
                            &nbsp;&nbsp;&nbsp;
                        </td>
                        <td>
                            <h3>
                                State
                                @Html.DropDownList("StateList", new SelectList(ViewBag.PigStateList, "Value", "Key"), "-- Select One --", new { @class = "form-control", required = "required", validationmessage = "State is required", placeholder = "State", tabindex = "3", @id = "state", style = "width:250%; height:35px;" })
                            </h3>
                            <p>


                            </p>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div class="text-right btn-toolbar">
            <button id="bLoadPrevious" class="btn btn-sm btn-default" type="button">Fill Last Week’s Figures</button>&nbsp; &nbsp;
            <button id="bClearData" class="btn btn-sm btn-default" type="button">Clear Data</button>&nbsp; &nbsp;
        </div>
        <br />
        <br />
        <div class="form-group col-md-12">
            <div style="width:100%;overflow:auto;">
                @(Html.Kendo().Grid<Project.Core.EF.weekly_pigprice_data>
    ()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.pig_type).Title("Pig Type");
        columns.Bound(p => p.pig_weight).Title("Pig Weight").Width(140);
        columns.Bound(p => p.price_type).Title("Price Type").Width(140);
        columns.Bound(p => p.price).Title("Price(cent/kg)").Width(50);
        columns.Bound(p => p.number_traded).Title("Numbers").Width(50);

    })
    .ToolBar(toolbar =>
    {
        toolbar.Save();
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .HtmlAttributes(new { style = "height:1250px;" })
    .DataSource(dataSource => dataSource
    .Ajax()
    .Batch(true)
    .Group(g => g.Add(p => p.pig_type))
    .PageSize(50)
    .ServerOperation(false)
    .Model(model =>
    {
        model.Id(p => p.id);
        model.Field(p => p.id).Editable(false);
        model.Field(p => p.week_end_date);
        model.Field(p => p.state);
        model.Field(p => p.pig_type).Editable(false);
        model.Field(p => p.pig_weight).Editable(false);
        model.Field(p => p.price_type).Editable(false);
        model.Field(p => p.price);
        model.Field(p => p.number_traded);

    })
    .Events(events => events.Error("error_handler"))
    .Create("Editing_Create", "MarketingPigPrice", new { id = ViewBag.ContactId })
    .Read(read => read.Action("PigPriceEdit_Read", "MarketingPigPrice", new { id = ViewBag.ContactId }))
    .Update("Editing_Update", "MarketingPigPrice")
    .Destroy("Editing_Destroy", "MarketingPigPrice")
    )
    )
    <br />
</div>
            <br />
        </div>

    </form>
</div>

Viktor Tachev
Telerik team
 answered on 05 Mar 2020
4 answers
112 views

Hello!
I have a problem with filters in my scheduler: as shown in your base example,

I use a first filter applied on a member field called LabelTypeID (the same as OnwerID in your example).

My Model has a second (int ?) member called LabelID
In some case I have to filter only the LabelID (to select a single label, associated to the Calendar Event)

So, in my template I added a second resource for the LabelID, where the binding returns all possible labels:

.Resources(resource =>
 
  {
 
      resource.Add(m => m.LabelTypeID)
 
      .DataTextField("Text")
 
      .DataValueField("Value")
 
      .DataColorField("Color")
 
      .BindTo((new ACSDoorSignage.BIZ.LabelTypeBiz()).GetAllLabelTypesAsRazorArray(false));
 
  
      resource.Add(m => m.LabelID)
 
      .DataTextField("Text")
 
      .DataValueField("Value")       
 
      .BindTo((new ACSDoorSignage.BIZ.LabelBiz()).GetLabelsAsRazorArray(false));
        
  })

This is the filter that I try to use, where labelValue is one of the value returned in the binding (eg 1)

if (labelValue != -1) {
 
          var filter = {
 
              logic: "or",
 
              filters: new Array()
 
          };
 
          filter.filters.push(
 
           {
              operator: "eq",
 
              field: "LabelID",
 
              value: labelValue
 
          });
      }
 
      var scheduler = $("#scheduler").data("kendoScheduler");
 
      scheduler.dataSource.filter(filter);

 

The filter Always fails and I see on the browser:

Uncaught TypeError: (d.LabelID || "").toLowerCase is not a function

Can you help me to unserstand what happened?

If I'd like to apply a filter, MUST I Always define a resource for that filter?

 

Martin
Telerik team
 answered on 05 Mar 2020
1 answer
81 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
3.0K+ 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.8K+ 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
493 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
148 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.1K+ 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
344 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
706 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
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
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
AICodingAssistant
+? 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?