This is a migrated thread and some comments may be shown as answers.

Getting custom message from controller

8 Answers 915 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Janusz
Top achievements
Rank 1
Janusz asked on 29 Dec 2015, 02:07 PM

Hi,

[b]I need to show a message after the creation of record using ajax callback. The text of message is made in mvc controlller.[/b]

My controler is simply:

 [code]       [HttpPost]
        public ActionResult User_Create([DataSourceRequest] DataSourceRequest request, UserRoleModel model)
        {
            if (model != null && ModelState.IsValid)
                try
                {
                    new LoginCommand().CreateUserData(model, UserSession, ref myMessage);
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError("", exception.Message);
                }
            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }
[/code]

The interface in razor looks like this

[code]                @(Html.Kendo().Grid(Model).Name("UzytkownicyGrid")
                .Columns(cols =>
                {
                    cols.Bound(p => p.UserLogin).Width(150).Locked();
                    cols.Bound(p => p.UserName).Width(200);
                    //                cols.Bound(p => p.Status).Width(60);
                    cols.Bound(p => p.Active).ClientTemplate("#=Active ? 'Tak': 'NIE'#").Width(80);
                    if (WlasneCommonFunc.IsAdministrator(ViewData))
                    {
                        cols.Command(command => command.Edit().Text("edytuj")).Width(120);
                    }
                    cols.Bound(p => p.MailAddress).Width(200).ClientTemplate("#= createMailLink(MailAddress) #");
                    cols.ForeignKey(p => p.RoleId, (IEnumerable)ViewData["roles"], "IdRoli", "Summary")
                        .Title("Uprawnienia").Width(150).MinScreenWidth(900);
                    cols.Bound(p => p.Mobilephone).Width(100).MinScreenWidth(1000).ClientTemplate("#= createPhoneLink(Mobilephone) #");
                    cols.Bound(p => p.Telephone).Width(100).MinScreenWidth(1100).ClientTemplate("#= createPhoneLink(Telephone) #");
                    cols.Bound(p => p.Funkcja).Width(100).MinScreenWidth(1200);
                    cols.Bound(p => p.MailDw).Width(200).MinScreenWidth(1300).ClientTemplate("#= createMailLink(MailDw) #");
                })
                .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("UzytkownicyEdit").Window(w => w.Title("Korekta uprawnieĊ„").Width(400)))
                .Groupable()
                .Resizable(resize => resize.Columns(true))
                .Reorderable(reorder => reorder.Columns(true))
                .Sortable()
                .Filterable()
                .ToolBar(toolbar =>
                {
                    if (WlasneCommonFunc.IsAdministrator(ViewData))
                    {
                        toolbar.Create();
                    }
                })
                .Navigatable()
                .Events(e => e.Edit("uzytkownikEdit"))
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .ServerOperation(false)
                    .Model(model => model.Id(p => p.Identity))
                    .Events(events => events.Error("errorHandler"))
                    .Read("Uzytkownicy_Read", "Profil")
                    .Update("Uzytkownicy_Update", "Profil")
                    .Create("Uzytkownicy_Create", "Profil")
                    .Group(groups => groups.Add(p => p.RoleId))
                    ))
[/code]

With displaying errors I have no problems.They are showed by the following function

[code]function errorHandler(e) {
    if (e.status = "error") {
        var message = "OPERACJA NIEUDANA\n";
        if (e.errors) {
            $.each(e.errors, function(key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function() {
                        message += this + "\n";
                    });
                }
            });
        } else
            message += e.errorThrown;
        alert(message);
    }
}
[/code]

What method is the best to do with it? Please help me out.

Regards,
Josef Jaskowiec
Rekord 

 

8 Answers, 1 is accepted

Sort by
0
Boyan Dimitrov
Telerik team
answered on 04 Jan 2016, 09:47 AM
Hello,

My suggestion is to use the requestEnd event of the Kendo UI DataSource and to check if the type of the request is  "create" to show the message. 

Regards,
Boyan Dimitrov
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
0
Janusz
Top achievements
Rank 1
answered on 07 Jan 2016, 01:32 PM

Thanks a lot - this works fine. Here is my requestEndHandler code

function requestEndHandler(evt) {
    if (evt.type === "create") {
        var data = evt.response.Data[0];
        window.notifyWidget.show('Dane do logowania zostaĊ‚y wysĊ‚ane na adres: ' + data.MailAddress);
    }
}

 

0
Duke
Top achievements
Rank 1
answered on 29 Mar 2017, 07:26 PM

Hi Janusz or Boyan, I hope you'll get this late question regarding this code.

I get how to handle a requestEnd event in the front end, and how to AddErrorModel on the .net backend.

But I don't see here how to actually add a custom message that is NOT an error, with something like AddMessage or something like that.

How else can data be fed from .Net MVC to the browser event?

Thanks.

0
Boyan Dimitrov
Telerik team
answered on 31 Mar 2017, 02:53 PM

Hello Duke,

The controller returns JsonResult object to the client-side. This represents the response object and key-value pairs should be fine to be added and read in the responseEnd event handler.  

Regards,
Boyan Dimitrov
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Duke
Top achievements
Rank 1
answered on 31 Mar 2017, 03:20 PM

Thanks for the quick response!

Your reply makes sense, and for most cases the responseEnd event code can read the returned key/value pairs and assume that everything went well and the transaction was successful.

 

What I'm talking about, though, is adding an additional message when a transaction succeeds.  Beyond the returned key/value(s), I would like to have a custom message from the controller.  So the ModelState object has an AddErrorModel method.  Is there a way to add a message which will also keep .isValid = true?

 

Thanks.

0
Boyan Dimitrov
Telerik team
answered on 04 Apr 2017, 08:32 AM

Hello,

As far as I understand the main idea is to extend the functionality of the ModelState object, which is related to the .NET ASP.NET MVC rather than the Kendo UI. 

Still I believe that what you are looking for is something like the question discussed in the Could i extension the ModelStateDictionary Class in MVC3 forum thread. I would like to encourage you to search for other similar discussions in case that this one does not provide the exact information you are looking for. 

 

Regards,
Boyan Dimitrov
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Greg
Top achievements
Rank 2
answered on 11 Jul 2018, 02:28 PM

Hi, I know this is a very late reply to this post but maybe this will help someone looking for the same answer

I threw together code that I found in different posts that works nicely. It will find any mvc grids on page and automatically assign a requestEnd event to the dataSource that will show any Model errors added in controller. (ex: ModelState.AddModelError("RoleId", "This user already has this role assigned");

<script>

    function showAlertWindow(message) {
        var alertWindow = $('#alertWindow').data('kendoWindow');
        alertWindow.content(message);
        alertWindow.refresh();
        alertWindow.center();
        alertWindow.open();
    }
    function error_handler(e) {
        if (e.response.Errors) {
            var message = "Errors:\n";
            $.each(e.response.Errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            showAlertWindow(message);
        }
    }

    $(document).ready(function () {           
        //find all kendo grids on page
        $(".k-grid").each(function () {
            var cb = $(this).data("kendoGrid");
            if (cb) {
                //programatically bind error handler to  grid 
                cb.dataSource.bind("requestEnd", error_handler);
            }
        });
    });


</script>

 

 

0
Greg
Top achievements
Rank 2
answered on 11 Jul 2018, 02:30 PM

Oops, forgot this part.... Need to add this on page as well.

@(Html.Kendo().Window()
                .Name("alertWindow")
                .Title("Status Message from Server")
                .Draggable()
                .Resizable()
                .Width(400)
                .Height(200)
                .Modal(true)
                .Visible(false)

Tags
Grid
Asked by
Janusz
Top achievements
Rank 1
Answers by
Boyan Dimitrov
Telerik team
Janusz
Top achievements
Rank 1
Duke
Top achievements
Rank 1
Greg
Top achievements
Rank 2
Share this question
or