paboobhzx
paboobhzx

Reputation: 119

Pass data from View to Controller using Ajax

I know this question has been asked here thousands of times ; i'm already following many things i've read but i still can't get this to work.

What i'm basically trying to do is send an FCM Token (that i obtained with a script on my basis Layout.cshtml) to the controller, by using Ajax. However, the value is always null. Even following the correct names i can't get the token data on the controller. So far so good this is what i've done.

HTML Page:

    @using RazorEngine.Templating
@inherits TemplateBase

@{
    Layout = "..\\Layout.cshtml";
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>
<script>
    function submitForm() {
        var currToken = messaging.getToken();
        var TokenModel = new Object();
        TokenModel.RegisteredToken = currToken;
        $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Notification/Register", // Controller/View 
                dataType: 'json',                
                data: JSON.stringify({
                    Token: TokenModel                    
                },
                success: function (status) {
                    console.log('Send');
                },
                error: function () {
                    console.log('something went wrong - debug it!');
                }
            });
    }
</script>
<div id="token"></div> 
<input type="button" value="Click" onclick="submitForm()" />

Controller (i'm sending everything to the Register Action)

public class NotificationController : BaseController
    {
        [HttpPost]
        [AllowAnonymous]
        public async Task<IHttpActionResult> Register(TokenModel Token)
        {

            //TokenModel currtoken = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenModel>(myToken);


            string token = "agamenon";
            string secondToken = "nosferatu";
            var execCtx = this.ExecutionContext;

            var pushNotifService = execCtx.GetExtension<IPushNotificationService>(); 



            var notificationTitle = "tituloX" + new Random().Next(1000, 5000);
            var notificationBody = "someContent" + new Random().Next(91000, 95000);
            var msg = new PushNotificationMessage()
            {
                Body = notificationBody,
                Title = notificationTitle
            };
            await pushNotifService.SendMessageAsync(msg, new string[] { token,secondToken });
            //var info = await pushNotifService.GetInfoAsync(token);
            //var invalidInfo = await pushNotifService.GetInfoAsync(secondToken);
            return View();
        }

And the TokenModel class:

public class TokenModel
{
    public string RegisteredToken { get; set; }
}

This site doesn't follow the MVC model, its an WebAPI. What am i doing wrong that i can't get the data sent to the controller ? AFAIK names are okay, everything is okay, its supposed to work.

Any input is appreciated.

Thanks

Upvotes: 0

Views: 464

Answers (1)

JGuarate
JGuarate

Reputation: 378

Could you show the output after this line of TokenModel

TokenModel.RegisteredToken = currToken;

E.g:

console.log(TokenModel);.

Nevertheless, I think what is happening in the data param is wrong. And your data object should be formed in this way, cause data needs to be a valid object:

Token: JSON.stringify(TokenModel)

data: { Token: JSON.stringify(TokenModel), },


UPDATE:

It seems like messaging.getToken() is calling an asynchronous function so to get the correct value you could use thenables to wait the promise to complete or async/await.

Example of your script using thenables:

function submitForm() {
    messaging.getToken().then(value => {
    const TokenModel = {
      RegisteredToken = value
    }
    $.ajax({
            type: "POST", //HTTP POST Method
            url: "Notification/Register", // Controller/View 
            dataType: 'json',                
            data: JSON.stringify({
                Token: TokenModel                    
            }),
            success: function (status) {
                console.log('Send');
            },
            error: function () {
                console.log('something went wrong - debug it!');
            }
        });
    }, error => {
      console.log('messaging.getToken() fails - debug it!');
      throw new Error(error);
    }    
}

Example of using await/async:

submitForm = async () => {
try {
    const token = await messaging.getToken();
    const TokenModel = {
    RegisteredToken = token
    };
    $.ajax({
        type: "POST", //HTTP POST Method
        url: "Notification/Register", // Controller/View 
        dataType: 'json',                
        data: JSON.stringify({
            Token: TokenModel                    
        }),
        success: function (status) {
            console.log('Send');
        },
        error: function () {
            console.log('something went wrong - debug it!');
        }
    });
} catch(error) {
    console.log('Invalid token');
    throw new Error(error);
}}

Upvotes: 1

Related Questions