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

I am using two project MVC Controller project and Web api Controller, I am having telerik MVC kendo grid(Client side grid), In the grid I have called web api (Server side), Get and Post is woking fine but PUT and DELETE is getting error. I have done the CORS but still getting error.

Please find the code snippet and error details below. 

MVC Controller Code :

@(Html.Kendo().Grid<EditableCity>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(c => c.iCityID).Hidden();
            columns.Bound(c => c.sCityDesc).Title("City Description");
            columns.Bound(c => c.sCountryCode).Title("Country");
            columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
        })
        .ToolBar(toolbar => { toolbar.Create(); })
        .Editable(ed => ed.Mode(GridEditMode.PopUp))
        .Selectable()
        .Filterable()
        .Pageable(pageable => pageable
            .Refresh(true)
            .PageSizes(true)
            .ButtonCount(5))            
        .DataSource(dataSource => dataSource
            .WebApi()
            .PageSize(20)
            .Model(m => m.Id(p => p.iCityID))
            .ServerOperation(false)
            .Read(read => read.Url("http://localhost:60018/api/city"))
            .Create(create => create.Url("http://localhost:60018/api/city").Type(HttpVerbs.Post))
            .Update(Update => Update.Url("http://localhost:60018/api/city/").Type(HttpVerbs.Put))
            .Destroy(del => del.Url("http://localhost:60018/api/city/").Type(HttpVerbs.Delete))            
        )
)

CORS in WebApiConfig - Register

 var cors = new EnableCorsAttribute("http://localhost:60018", "*", "*");
            config.EnableCors(cors);

Web API controller Code:

//[RoutePrefix("api/catalog")]
    public class CityController : ApiController
    {
        CityBL cityBL = new CityBL();

        // GET: api/City
        //[Route("city")]
        [ResponseType(typeof(IQueryable<EditableCity>))]
        [CacheFilter(TimeDuration = 10)]
        //[Authorize]
        public async Task<DataSourceResult> Get([ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request)
        {
            var susername = HttpContext.Current.User.Identity.Name;
            var gridData = await cityBL.GetCity();
            var result = new DataSourceResult()
            {
                Data = gridData,
                Total = gridData.Count()
            };

            return result;
        }

        // GET: api/City/5
        //[Route("city/{id}")]
        [ResponseType(typeof(EditableCity))]
        public async Task<IHttpActionResult> Get(int id)
        {
            var result = await cityBL.GetCityById(id);
            return Json(result);
        }

        // POST: api/City
        public async Task<IHttpActionResult> Post(EditableCity value)
        {
            if (value.iCityID > 0)
                await cityBL.UpdateCity(value);
            else
                await cityBL.InsertCity(value);

            return Json(value);
        }

        //// PUT: api/City/5
        //public async Task<IHttpActionResult> Put(EditableCity value)
        //{
        //    await PutCity(value.iCityID, value);
        //    return Json(value);
        //}
       
        // DELETE: api/City/5
        [HttpDelete]
        public async Task<IHttpActionResult> Delete(int id)
        {
            await cityBL.DeleteCity(id);
            return Ok();
        }
    }

 

I am getting error.(PUT and Delete)

OPTIONS http://localhost:60018/api/city/ 400 (Bad Request)

XMLHttpRequest cannot load http://localhost:60018/api/city/. Response for preflight has invalid HTTP status code 400

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at Function.parse [as parseJSON] (<anonymous>)
    at init.error_handler (City:76)
    at init.trigger (kendo?v=GlJVUnHmCTfOQhn3vJxT3TaOscBWvurIgbVIZ_jm6_41:1)
    at init.error (kendo?v=GlJVUnHmCTfOQhn3vJxT3TaOscBWvurIgbVIZ_jm6_41:1)
    at Object.error (kendo?v=GlJVUnHmCTfOQhn3vJxT3TaOscBWvurIgbVIZ_jm6_41:1)
    at c (Scripts?v=rDiPocDqq4l1v5wzpbjulXqJqaXM1N6IzVYG_owHFO81:1)
    at Object.fireWith [as rejectWith] (Scripts?v=rDiPocDqq4l1v5wzpbjulXqJqaXM1N6IzVYG_owHFO81:1)
    at b (Scripts?v=rDiPocDqq4l1v5wzpbjulXqJqaXM1N6IzVYG_owHFO81:1)
    at XMLHttpRequest.<anonymous> (Scripts?v=rDiPocDqq4l1v5wzpbjulXqJqaXM1N6IzVYG_owHFO81:1)

 

Thanks

Suman

Boyan Dimitrov
Telerik team
 answered on 28 Mar 2017
1 answer
869 views
@(Html.Kendo().Grid<BranchDirectoryProject.Domain.Models.BranchListModel>
        ()
        .Name("GridOfBranchList")
        .Editable(editable => editable.Mode(GridEditMode.InCell))
        .Events(e => e.Save("onSave"))
        .Columns(columns =>
        {
            columns.Bound(c => c.BranchID);
            columns.Bound(c => c.OpCo)
            .Width(120);
        })
        //.ToolBar(tools => tools.Excel())
        .ToolBar(toolBar =>
        {
            toolBar.Create();
            toolBar.Save();
        })
        .HtmlAttributes(new { style = "height: 550px;" })
        .Scrollable()
        .Groupable()
        .Sortable()
        .Pageable(pageable => pageable
        .Refresh(true)
        .PageSizes(true)
        .ButtonCount(5))
        .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
        {
            model.Id(c => c.BranchID);
        })
 
        .Read(read => read.Action("GridOfBranchList_Read", "Home"))
        .Create(create=> create.Action("BranchUpdate", "Home").Data("AdditionalData"))
        .Update(update => update.Action("BranchUpdate", "Home"))
        .PageSize(20)
        ))

</div>
    <script>
        var eventobject;
        function AdditionalData(e) {
            alert("this is an alert");
            console.log(eventobject.model.BranchID);
            return {
                branch: eventobject.model.BranchID,
                OpCo : eventobject.model.OpCo
            }
        }
function onSave(e) {
            
            
            //if (e.model.BranchID != null) {
             //   branchBox = e.model.BranchID;
           // }
           // if (e.model.OpCo != null) {
          //      opcoBox = e.model.OpCo;
           // }
            console.log("Event Object");
            console.log(typeof(e));
            console.log("BranchBox");
            console.log(branchBox);
            console.log("e.model.BB");
            console.log(e.model.BranchID);
            console.log("opcoBox");
            console.log(opcoBox);
            console.log("e.model.OCB");
            console.log(e.model.OpCo);
            console.log(e.values.BranchID);
            eventobject = e;

Hi,

This is what my current kendo grid looks like. The scenario involves a sql table with the aim of displaying the contents of that table and providing the functionality to insert rows containing user entered data. Currently, I am providing that functionality with the toolbar kendo provides. I have a helper class in my controller which I am using to take the data from the client and place it in the action method. You can see the AdditionalData function which I have placed in my view and the onSave event below it. Those two are related to the helper class in the controller and I am using them to get the KendoGrid data back to my controller. I am not confident that this is the cleanest way to perform all of this, and any suggestions on that front are welcome. 

However, my functionality is present in the current solution I have. I just dont understand why its not giving me errors when a user tries to add two rows at the same time. When the user clicks the add row button twice, it spawns two empty rows in the grid. If they go down and put data into both rows and then click save, both rows will be conveniently inserted into my database without crashing anything. How is this possible? The eventObject in the onSave event will be assigned twice and overwritten once. Yet the additionalData function will properly be called twice with distinct values of the eventObject each time. 

Can anyone walk me through this code so that I can learn a little more? I want to know why additionalData doesnt get called twice with whatever value is last written to the eventObject variable. Will it continue to perform properly no matter how many empty rows are created with a single click of the save button? Or will it break at some limit or on some network conditions? I suspect there is a race condition. Lets talk about that.

And can anyone tell me how to disable the addRow Button in the toolbar? It would be great if the user could only click this once per click of the save button. So that they can only insert one row at a time. And can anyone tell me how to create a custom toolbar button that is basically a wrapper around the pre-defined toolbar buttons? Or how can I recreate the create toolbar button such that all of the interesting things that it does for me are exposed in my source code, so that I may properly fiddle with it? I would really like to be able to crack open the create toolbar button and see all of the things going on inside of it so that I can better understand the grid and so I can better devise custom solutions. I like having the knowledge of custom solutions in my back pocket because it means less time browsing the forums for out of the box solutions.

Thank you. Let me know if I can clarify anything.

Stefan
Telerik team
 answered on 28 Mar 2017
2 answers
1.0K+ views

Hi,

I use filtering on kendo grid in row mode. This works fine, except one detail. I want to have the list sorted, not in that order you can see in the attached screen. I've noticed that if I changed the sort option to "Sort(sort => sort.Add("ClientName")", the autocomplete would get the items alphabetically. But what about another fields, where I also want to have the right order. And of course I don't want to change the global order.

@(Html.Kendo().Grid<PostTaskModel>().Name("AktualneGrid")
    .Columns(cols =>
    {
        cols.Bound(p => p.CaseNumber).Width(80).ClientTemplate("#=gotoTaskWindow(data.CaseNumber, data.Ident)#")
            .HtmlAttributes(new { @class = "link-cell" }).Locked().Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
        cols.Bound(p => p.Subject).Width(200).ClientTemplate("<b>#=Subject#</b>").Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
        cols.Bound(p => p.DocumInfo).Width(50).Title("Niep.wiad.").ClientTemplate("#=BoldNotRead(data.DocumInfo, data.NoReadCnt)#");
        cols.Bound(p => p.Description).Width(600).ClientTemplate("#:Truncate(Description, descLength)#").Title("Opis zgÅ‚oszenia . . . . .")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
        cols.Bound(p => p.ModifyDate).Width(60).Format("{0:yyyy-MM-dd HH:mm}");
        cols.Bound(p => p.Applicant).Width(100).Filterable(ftb => ftb.Multi(true));
        cols.Bound(p => p.FinishTerm).Width(60).ClientTemplate("#=BoldBeforeNow(data.FinishTerm)#");
        cols.Bound(p => p.EmployeeName).Width(100).Filterable(ftb => ftb.Multi(true));
        cols.Bound(p => p.ClientName).Width(150).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")));
        cols.ForeignKey(p => p.IssueKindId, (IEnumerable)ViewData["casetypes"], "Ident", "Description")
            .Title("Nazwa rodzaju").Width(200).Filterable(ftb => ftb.Multi(true)).Hidden();
        cols.ForeignKey(p => p.Priority, (IEnumerable)ViewData["priorities"], "Symbol", "Description")
            .Title("Opis kategorii").Width(100).Filterable(ftb => ftb.Multi(true));
        cols.Bound(p => p.ProductName).Width(200).Filterable(ftb => ftb.Multi(true));
    })
    .Sortable()
    .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
    .Pageable(pager => pager.PageSizes(new[] { 10, 15, 20, 30, 50 }).Input(true).Refresh(true))
    .Groupable()
    .Resizable(resize => resize.Columns(true))
    .Reorderable(reorder => reorder.Columns(true))
    .ColumnMenu()
    .Navigatable()
    .Selectable(sel => sel.Mode(GridSelectionMode.Multiple).Type(GridSelectionType.Cell))
    .AllowCopy(true)
    .HtmlAttributes(new { style = "min-width:1840px;" })
    .Events(e => e.DataBound("gridFocusDataBound"))
    .AutoBind(false)
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model => model.Id(p => p.Ident))
        .ServerOperation(false)
        .Sort(sort => sort.Add("ModifyDate").Descending())
        .Read(read => read.Action("Aktualne_Read", "Async").Data("filterGrid"))
        .Events(events => events.Error("errorHandler"))
))

I will be grateful for your help

Josef

Janusz
Top achievements
Rank 1
 answered on 28 Mar 2017
4 answers
643 views

Hi,

I have a datepicker on a page which was working perfectly until yesterday. Suddenly it stopped showing existing dates in Chrome. if I select new date from the picker it works fine. I get a javascript error in the browser. I have posted similar questions with javascript error couple of years back. http://www.telerik.com/forums/date-format-error-with-date-picker 

It was resolved at that time using the Format.

@(Html.Kendo().DatePickerFor(m => m.BirthDate)
      .Name("BirthDate")
     .Value(Model.BirthDate)
     .Format("MM/dd/yyyy")
     .HtmlAttributes(new { @class = "form-control" }) )

Now as per the suggestion in the above link, i have change the code like this

@(Html.Kendo().DatePickerFor(m => m.BirthDate)
     .Name("BirthDate")
    .HtmlAttributes(new { type = "text" })
    .Value(Model.BirthDate)
    .Format("MM/dd/yyyy")
    .HtmlAttributes(new { @class = "form-control" }))

 

But still no use. I still don't see the dates.

Vasil
Telerik team
 answered on 28 Mar 2017
1 answer
470 views

The following dropdownlist works fine:

 

    @(Html.Kendo().DropDownList()
            .Name("TrunkDepotsList")
            .HtmlAttributes(new { style = "width: 70px;" })
            .DataTextField("DepotNumber")
            .DataValueField("DepotID")
            .BindTo(Model.DepotList)
            .SelectedIndex(Model.DepotIndex)
    )

 

However - when I add an event handler, it turns into a textbox:

 

    @(Html.Kendo().DropDownList()
            .Name("TrunkDepotsList")
            .HtmlAttributes(new { style = "width: 70px;" })
            .DataTextField("DepotNumber")
            .DataValueField("DepotID")
            .BindTo(Model.DepotList)
            .SelectedIndex(Model.DepotIndex)
            .Events(e =>
            {
                e.Change("refreshTrunkSummaryPage");
            })
    )

 

For reference, here's my event handler script:

 

function refreshTrunkSummaryPage() {
        alert('refresh running');

        ...etc

}

Nencho
Telerik team
 answered on 28 Mar 2017
2 answers
174 views

http://demos.telerik.com/aspnet-mvc/combobox/serverfiltering

The view and the controller do not seem to work together.  The view is calling a controller action that does not exist, the controller action that does exist is not returning any data.

Or if I'm wrong, I'll humbly accept corrections :-)

Duke
Top achievements
Rank 1
 answered on 27 Mar 2017
1 answer
630 views

I'm trying to use the Telerik MVC TreeView control with the kendo.data.HierarchicalDataSource control and local data.

In samples for the Kendo Treeview, they point to the Javascript datasource like this:

dataSource: homogeneous

What syntax do I use in the fluent MVC TreeView to reference data that's held in a JavaScript variable?

Showing my hierarchical data below.

Thanks,

Ken

{ 
   "bodyType":"ESTATE",
   "capCode":"VWTI20SE5EDTM4",
   "capID":null,
   "co2Emissions":"167",
   "colour":"SILVER",
   "cylinderCapacity":"1968 cc",
   "dateFirstUsed":"23 July 2009",
   "dateOfFirstRegistration":"23 JULY 2009",
   "description":"2009 Volkswagen Tiguan Se Tdi (140) 4MOTION, 1968CC Diesel, 5DR, Manual",
   "engineSize":"1968CC",
   "fuel":"Diesel",
   "fuelType":"DIESEL",
   "imported":"false",
   "insuranceGroup":"09",
   "licencePlate":"mt09nks",
   "make":"Volkswagen",
   "model":"Tiguan",
   "mot":true,
   "motDetails":"Expires: 28 April 2017",
   "motTestReports":[ 
      { 
         "motTestNumber":244794981138,
         "testResult":"Pass",
         "testDate":"29 April 2016",
         "odometerReading":80084,
         "expiryDate":"28 April 2017",
         "advisoryItems":[ 
 
         ],
         "failureItems":[ 
 
         ]
      },
      { 
         "motTestNumber":938552815158,
         "testResult":"Pass",
         "testDate":"22 April 2015",
         "odometerReading":74998,
         "expiryDate":"21 April 2016",
         "advisoryItems":[ 
 
         ],
         "failureItems":[ 
 
         ]
      },
      { 
         "motTestNumber":157384685012,
         "testResult":"Fail",
         "testDate":"25 March 2015",
         "odometerReading":74813,
         "expiryDate":"",
         "advisoryItems":[ 
            "Front Brake pad(s) wearing thin (3.5.1g)",
            "Front brake disc worn, pitted or scored, but not seriously weakened (3.5.1i)",
            "Rear brake disc worn, pitted or scored, but not seriously weakened (3.5.1i)",
            "Rear Brake pad(s) wearing thin (3.5.1g)",
            "Nearside Front Suspension arm rubber bush deteriorated but not resulting in excessive movement (2.4.G.2)",
            "Offside Front Suspension arm rubber bush deteriorated but not resulting in excessive movement (2.4.G.2)"
         ],
         "failureItems":[ 
            "Nearside Front Tyre tread depth below requirements of 1.6mm (4.1.E.1)",
            "Offside Front Tyre tread depth below requirements of 1.6mm (4.1.E.1)",
            "Front Brakes imbalanced across an axle (3.7.B.5b)",
            "Nearside Front Windscreen wiper does not clear the windscreen effectively (8.2.2)"
         ]
      },
      { 
         "motTestNumber":195455474181,
         "testResult":"Pass",
         "testDate":"24 June 2014",
         "odometerReading":63643,
         "expiryDate":"23 July 2015",
         "advisoryItems":[ 
 
         ],
         "failureItems":[ 
 
         ]
      },
      { 
         "motTestNumber":198414503254,
         "testResult":"Pass",
         "testDate":"23 July 2013",
         "odometerReading":52191,
         "expiryDate":"23 July 2014",
         "advisoryItems":[ 
 
         ],
         "failureItems":[ 
 
         ]
      },
      { 
         "motTestNumber":945398182180,
         "testResult":"Pass",
         "testDate":"6 July 2012",
         "odometerReading":308600,
         "expiryDate":"23 July 2013",
         "advisoryItems":[ 
 
         ],
         "failureItems":[ 
 
         ]
      }
   ],
   "numberOfDoors":"5",
   "numberOfSeats":"5",
   "price":"6465.0",
   "steering":"RHD",
   "transmission":"MANUAL",
   "typeApproval":"M1",
   "vin":"WVGZZZ5NZAW007903",
   "year":"2009",
   "yearOfManufacture":"2009"
}
Nencho
Telerik team
 answered on 27 Mar 2017
1 answer
184 views

I have tabstrip that is displaying a partial from a different controller/view area, but I cant get the post of the partial in the tabstrip to post back to the different controller

 

the View that the tab is in.

~/Areas/Secure/Views/Company/companyStaff.cshtml

display a view assocated to a different controller

tabstrip.Add().Text("Create Contact")
                  .Selected(false)
                  .Content(Html.Partial("~/Areas/Secure/Views/Contact/_ContactManagement.cshtml",  new WebSite.Library.Models.Contact() , new ViewDataDictionary { { "Id", "0" } }).ToHtmlString());

 

How can I get the partial in the tab to post back to its own controller post method

Ivan Danchev
Telerik team
 answered on 27 Mar 2017
4 answers
941 views

Hi,

I am using the Pdf export to print a grid. In the page header on each page I would like to have content from the model (or the ViewBag or some other way), in any case data that I can set in the method in the controller when I load the ViewModel for the page. I have found a lot of info about the page headers, but the page number is the only variable data I have seen.

I would like to show something like "Inventory as of Dec 3rd, report printed March 21st", so not only page number and today's date but other stuff too.

Is this possible and if so, can someone please point me in the right direction for info on this?

 

Best regards,

Henrik

Henrik
Top achievements
Rank 1
 answered on 27 Mar 2017
1 answer
1.4K+ views

How do i get the value of a Kendo Date Picker by class name. The reason being is because im using the name and id attributes for something else. As you can see below the class attribute is dynamic. Every other time ive selected a Kendo Date Picker, i've always used the ID attribute. Is it possible to select by class attribute?

@Html.Kendo().DatePicker()
              .Name("SurveyResponse.DateRes[" + @guid + "].Date")
              .Format("MM/dd/yyyy")
              .HtmlAttributes(new {
                       onkeydown = "javascript:return false;",
                       onblur = "ConditionalTextBox(" + @item.SurveyQuestionID + ",'datecontrol')",
                       @placeholder = "Your answer",
                       @required = "required",
                       @class = "IsConditionalTextBox_" + @item.SurveyQuestionID
                       })
Konstantin Dikov
Telerik team
 answered on 24 Mar 2017
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
ComboBox
Upload
MultiSelect
ListView
Window
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
Dialog
MultiColumnComboBox
DropDownTree
Checkbox
Slider
Switch
Notification
Accessibility
ListView (Mobile)
Pager
Security
ColorPicker
DateRangePicker
Wizard
Styling
Chat
DateInput
MediaPlayer
TileLayout
Drawer
SplitView
Template
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Licensing
Rating
ScrollView
ButtonGroup
CheckBoxGroup
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
SmartPasteButton
PromptBox
SegmentedControl
LLM Kit
+? more
Top users last month
Jake
Top achievements
Rank 1
RBarnes
Top achievements
Rank 1
Iron
Iron
Rami
Top achievements
Rank 1
Iron
Veteran
Nathan
Top achievements
Rank 1
Kumeri
Top achievements
Rank 1
Iron
Veteran
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jake
Top achievements
Rank 1
RBarnes
Top achievements
Rank 1
Iron
Iron
Rami
Top achievements
Rank 1
Iron
Veteran
Nathan
Top achievements
Rank 1
Kumeri
Top achievements
Rank 1
Iron
Veteran
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?