We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

How to change Toast Content dynamically

Hi 
The Toast content is staying as default value assigned. But i want to populate Toast content according to login fail. or any message thrown from webapi response. How to do it?
i have this in index.razor

           
       

@code {
    .....
    .....
    EjsToast toastObj;
    string ToastContent = "Default . But i dont want to display this";

    async Task SubmitLogin()
    {
        try
        {
            await state.Login(loginParameters);
            
            uriHelper.NavigateTo("/dashboard");
        }
        catch (Exception ex)
        {
            ToastContent = "Login Attempt Failed. I want to display this." + ex.Message;
            this.toastObj.Show();
        }
    }

}

10 Replies

BS Buvana Sathasivam Syncfusion Team July 10, 2019 09:23 AM UTC

Hi Subhash, 

Thank you for using Products from Syncfusion.   

We have validated the reported issue in “Dynamic update for template properties” at EJ2 Toast component, and we are considering this as a defect in our end.  The fix for the issue will be included in our next NuGet release on July 15th 
 
You can now track the current status of the report, review the proposed resolution timeline, and contact us for any further inquiries through this link: https://www.syncfusion.com/feedback/7290/issue-with-dynamic-update-for-template-properties     


Regards, 
Buvana S 
 



BS Buvana Sathasivam Syncfusion Team July 18, 2019 09:52 AM UTC

Hi Subhash, 

We have fixed the reported issue and it is included in the version 17.2.34-beta.   

Please check the following sample: 

We suggest you upgrade to the latest NuGet version at your end. Let us know if you need any further assistance. 

Regards, 
Buvana S 
 



DD DLMSOFT DEV September 13, 2019 12:28 PM UTC

Hi, 

using the 17.2.50 beta, the content of the toast can be dynamically changed but the first time I show the toast, the default content is displayed and not the one I set. The 2nd time, all is OK.

EjsToast ToastWindow;
string ToastContent = "Default message";
 protected void ShowToast()
{
            this.ToastContent = "New message (1st time)";
            this.ToastWindow.Show(); // Toast displays Default Message and not New Message (1st time)
            this.ToastWindow.Hide();

            this.ToastContent = "New message (2nd time)";
            this.ToastWindow.Show(); // Toast displays New Message (2nd time)
}


PM Pandiyaraj Muniyandi Syncfusion Team September 16, 2019 09:10 AM UTC

Hi DLMSOFT DEV, 
 
Greetings from Syncfusion support.  
  
We have validated your reported issue with shared code blocks and able to reproduce the issue from our end. The new content value is not updated in the Toast model to update the value dynamically and show method invoked immediately. So we suggest you call toast Show() method after some delay as follows 
 
 
    private async Task ShowToast() 
    { 
        this.ToastContent = "New message (1st time)"; 
        await Task.Delay(100); // Delay to update the content changes in Toast model 
        this.ToastWindow.Show(); 
    } 
 
 
  
We have prepared sample for your reference, get it from below link  
 
Regards, 
Pandiyaraj M 



NC NKOUAMBIA CHIMENE October 11, 2019 08:03 PM UTC

Hello,

Please How can I get the Id of My Toast Syncfusion Object in JS file ?? I set a Id Property but it always return a null value.
<EjsToast @ref="ToastObj" Title="Alerte Information" TimeOut=5000 Icon="e-meeting" Content="@ToastContent" ShowCloseButton="true">
    <ToastPosition X="Center" Y="Top"></ToastPosition>
</EjsToast>
@code{
EjsToast ToastObj;
        public string ToastContent { get; set;} = "Conference Room 01 / Building 135 10:00 AM-10:30 AM";  
 }

* my JS files ***
function SendMessageToOtherMembers(groupName, message) {
     var elt2 = document.getElementById("ToastObj"); // elt2 is null    
}; 

Thanks,
Chimène NK.


PM Pandiyaraj Muniyandi Syncfusion Team October 14, 2019 11:35 AM UTC

Hi Chimène, 
 
Good day to you. 

We have validated the reported issue with shared code block and we noticed you have used 
JSInterop for invoking javascript codes. The issue occurs due to missing the ID property configure in Toast component and @ref used for taking an instance in razor page. So we suggest you configure ID property in Toast component and use this ID in JS file as follows 
 
 
Index.razor 
<EjsToast @ref="ToastObj" ID="MyToast"> 
</EjsToast> 
 
Jsinterop.js 
function SendMessageToOtherMembers(groupName, message) { 
     var elt2 = document.getElementById("MyToast ");  
};  
 
 
  
We have prepared sample for your reference, get it from below link 
 
Regards, 
Pandiyaraj M 



NC NKOUAMBIA CHIMENE October 15, 2019 01:47 PM UTC

Hello!!

Is there a possibility to change the Content of my Toast Object in JS Code ??
 like 
Index.razor 
<EjsToast @ref="ToastObj" ID="MyToast" Content="@ToastContent"> 
</EjsToast> 
@code{
public string ToastContent { get; set;} = "Conference Room 01 / Building 135 10:00 AM-10:30 AM";
    EjsToast ToastObj;      
}
message.js
function SendMessageToOtherMembers(groupName, message) {
     var elt2 = document.getElementById("MyToast");      
     elt2.Content = "Hello !!"; // like this or another way ??
};
 
Thanks,
Chimène NK.


PM Pandiyaraj Muniyandi Syncfusion Team October 16, 2019 08:47 AM UTC

Hi Chimène, 
 
Good day to you. 
 
Yes, you can change the content by taking component instance. Update the content property value of Toast component and call “dataBind” from JavaScript file as follows. 
 
 
Index.razor 
<EjsToast @ref="ToastObj" ID="MyToast"> 
</EjsToast> 
 
Jsinterop.js 
function SendMessageToOtherMembers(groupName, message) { 
     var toastObj = document.getElementById("MyToast").ej2_instances[0]; 
    toastObj.content = "Hello !!";           // Take instance and update new value to content property 
    toastObj.dataBind();                          // Call dataBind method update changes in component instance 
};  
 
 
We have prepared sample for your reference, get it from below link 
 
Also, you can change the toast content dynamically from razor page, kindly refer this how-to documentation 
 
Regards, 
Pandiyaraj M 



NC NKOUAMBIA CHIMENE October 16, 2019 02:18 PM UTC

Hello Team!
Thanks for answer, I Have another request. Is there a Way to have the Toast.Show in Js file?? 
let me explain my scenario:
- I'm using blazor server side and SignalR to Inform users about Update/Delete of an data that they are consulting. So I want just to show the Toast Object for all users of group except the sender. when I let the this.ToastObj.Show in razor page it's only show the Toast object of the sender that is show.1
 1. the one I highlight in green work correctly as I want. It will just show the message in other members group page
 Q1. I Want the Toast to also works like that 

Razor page
<input type="button" id="sendmsg" value="Send Message" @onclick="Envoyer"/>
   
<div class="row">
    <div class="col-6">
        <ul id="messagesList"></ul>
    </div>
</div>
<EjsToast @ref="ToastObj" ID="MyToast" Title="Alerte Information" TimeOut=10000 Icon="e-meeting" Content="@ToastContent" ShowCloseButton="true">
    <ToastPosition X="Center" Y="Top"></ToastPosition>
</EjsToast>

@code{
    public string ToastContent { get; set;} = "Conference Room 01 / Building 135 10:00 AM-10:30 AM";
    EjsToast ToastObj;    
    private string groupName = "sm_salle";
    private string message = "Someone Just Update Informations"; 
   
    private async Task Envoyer(){
        await JsRuntime.InvokeAsync<string>("SendMessageToOtherMembers", groupName, message); 
      /* ToastContent =    this.StateHasChanged(); */ 
      this.ToastObj.Show(); 
        await Task.Delay(100);             
    }
   
}

message.js
connection.on("ReceiveMessage", function(message, groupName) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
     var encodedMsg = groupName + " says " + msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);  
  //To load message to Toast of other members of groups
    try {
        var toastObj = document.getElementById("MyToast").ej2_instances[0];
        toastObj.content = msg;
        toastObj.dataBind();
        await wait(500)
        toastObj.Show(); // Like this in order to show the toastObj on page of all users groups except the sender
    }
    catch (e) {
       console.log(e);
    }
});
function SendMessageToOtherMembers(groupName, message) {
    connection.invoke("SendMessageToOtherMembersGroup", groupName, message).then(function(connectionId) { 
                                                            console.log("Hello All of you I'm "+ connectionId);  })
                                                            .catch(function (err) {
                                                                        return console.error(err.toString());
                                                                    });  
    return "Bienvenue dans le gpe " + message;
};

ChatHub.cs
public async Task SendMessageToOtherMembersGroup(string groupName, string message)
        {
            List<string> listConnectionId = new List<string>(){Context.ConnectionId};
            IReadOnlyList<string> excludedIds = listConnectionId;
            await Clients.GroupExcept(groupName, excludedIds).SendAsync("ReceiveMessage", string.Format("{0}: {1}",Context.ConnectionId, message) , groupName);          
        }
Q2. I use this scenario in a Scheduler Component with so that when multi user select the same data(appointment) to visualize and then One of them update it, it send message to other to inform about the new state, but I get the error below even if my <li> Tag load the message , I don't know the origin (just to mentioned that in my proof of concept in my index page I don't Have that error)

Uncaught (in promise) Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> Newtonsoft.Json.JsonReaderException: Could not convert string to DateTime: +010000-01-01T04:59:59.999Z. Path 'value', line 1, position 38.
   at Newtonsoft.Json.JsonReader.ReadDateTimeString(String s)
   at Newtonsoft.Json.JsonTextReader.FinishReadQuotedStringValue(ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ReadAsDateTime()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Syncfusion.EJ2.Blazor.BaseComponent.TriggerHandler[T](String eventName, String arg)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Syncfusion.EJ2.Blazor.BaseComponent.InvokeGenericMethod(String name, Type type, Type parentType, Object[] arguments)
   at Syncfusion.EJ2.Blazor.BaseComponent.Trigger(String eventName, String arg)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.InvokeSynchronously(JSRuntime jsRuntime, DotNetInvocationInfo& callInfo, IDotNetObjectReference objectReference, String argsJson)
   at Microsoft.JSInterop.Infrastructure.DotNetDispatcher.BeginInvokeDotNet(JSRuntime jsRuntime, DotNetInvocationInfo invocationInfo, String argsJson)
    at Object.endInvokeDotNetFromJS (http://localhost:5000/_framework/blazor.server.js:8:28977)
    at e.<anonymous> (http://localhost:5000/_framework/blazor.server.js:8:103505)
    at http://localhost:5000/_framework/blazor.server.js:1:19148
    at Array.forEach (<anonymous>)
    at e.invokeClientMethod (http://localhost:5000/_framework/blazor.server.js:1:19119)
    at e.processIncomingData (http://localhost:5000/_framework/blazor.server.js:1:17165)
    at e.connection.onreceive (http://localhost:5000/_framework/blazor.server.js:1:10276)
    at WebSocket.i.onmessage (http://localhost:5000/_framework/blazor.server.js:1:38027)
endInvokeDotNetFromJS @ blazor.server.js:8
(anonymous) @ blazor.server.js:8
(anonymous) @ blazor.server.js:1
e.invokeClientMethod @ blazor.server.js:1
e.processIncomingData @ blazor.server.js:1
connection.onreceive @ blazor.server.js:1
i.onmessage @ blazor.server.js:1

Thanks,
Chimène NK.

Attachment: ErrorBlazor_1935bc22.7z


PM Pandiyaraj Muniyandi Syncfusion Team October 18, 2019 02:44 AM UTC

Hi Chimène, 
 
Good day to you. 
 
Query 1: Is there a Way to have the Toast.Show in Js file??  
 
Yes, you can display the Toast component by calling show() method with its instance from JavaScript file as follows 
 
 
Index.razor  
<EjsToast @ref="ToastObj" ID="MyToast">  
</EjsToast> 
  
Jsinterop.js  
connection.on("ReceiveMessage", function (message, groupName) { 
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); 
    try { 
        var toastObj = document.getElementById("MyToast").ej2_instances[0]; 
        toastObj.title = groupName; 
        toastObj.content = msg; 
        toastObj.dataBind(); 
        toastObj.show(); 
    } 
    catch (e) { 
        console.log(e); 
    } 
}); 
 
 
 
We have prepared sample for your reference, get it from below link 
 
Query 2: I use this scenario in a Scheduler Component with so that when multi user select the same data(appointment) to visualize and then One of them update it, it send message to other to inform about the new state, but I get the error below even if my <li> Tag load the message , I don't know the origin (just to mentioned that in my proof of concept in my index page I don't Have that error) 
 
We suspect that there might be some typecasting problem with your datasource which could result the reported problem. We have prepared a sample to send the data to other user for your reference which can be downloaded from the following link.  
 
     
    EjsSchedule<AppointmentData> ScheduleObj;  
    View CurrView = View.Week;  
    DateTime SelectedDate = new DateTime(2019, 1, 31);  
    HubConnection connection;  
  
    protected override async Task OnInitializedAsync()  
    {  
        connection = new HubConnectionBuilder().WithUrl("https://localhost:44363/ScheduleHub").Build();  
        connection.On<List<AppointmentData>>("RecieveData", OnDataChange);  
        connection.On<View>("ChangeView", OnChangeView);  
        connection.On<DateTime>("ChangeDate", OnChangeDate);  
        await connection.StartAsync();  
    }  
    public void OnActionCompleted(ActionEventArgs<AppointmentData> args)  
    {  
        if (args.RequestType == "eventCreated" || args.RequestType == "eventRemoved" || args.RequestType == "eventChanged")  
        {  
            connection.InvokeAsync("SendData", DataSource);  
        }  
    }  
    public void OnNavigating(NavigatingEventArgs args)  
    {  
        if (args.Action == "view")  
        {  
            connection.InvokeAsync("SendViewData", Enum.Parse(typeof(View), args.CurrentView, true));  
        }  
        if (args.Action == "date")  
        {  
            connection.InvokeAsync("SendSelectedDateData", args.CurrentDate);  
        }  
    }  
    Task OnChangeView(View view)  
    {  
        this.CurrView = view;  
        this.ScheduleObj.Refresh();  
        return Task.CompletedTask;  
    }  
    Task OnChangeDate(DateTime date)  
    {  
        this.SelectedDate = date;  
        this.ScheduleObj.Refresh();  
        return Task.CompletedTask;  
    }  
    Task OnDataChange(List<AppointmentData> data)  
    {  
        this.DataSource = data;  
        this.ScheduleObj.Refresh();  
        return Task.CompletedTask;  
    }  
 
  
ScheduleHub.cs  
 
public class ScheduleHub:Hub  
    {  
        public async Task SendData(List<Index.AppointmentData> data)  
        {  
            await Clients.Others.SendAsync("RecieveData", data);  
        }  
  
        public async Task SendViewData(View data)  
        {  
            await Clients.Others.SendAsync("ChangeView", data);  
        }  
  
        public async Task SendSelectedDateData(DateTime data)  
        {  
            await Clients.Others.SendAsync("ChangeDate", data);  
        }  
    }  
 
  
Kindly try the sample and share the code snippet of your hub page and scheduler code if the issue persist still at your end.  
 
Regards, 
Pandiyaraj 


Loader.
Live Chat Icon For mobile
Up arrow icon