locked
asp.net core razor pages model bindproperty on ajax update refresh RRS feed

  • Question

  • User-2029935383 posted

    Hello all,

    I am trying to get updated values after ajax update and update them in the html.

    Here's an example:

    in the cshtml file 

    <div id="name">

    @Model.name

    </div>

    <button type="submit" onclick="updateinfo();">submit</button>

    $.ajax({
    type: form.attr('method'),
    url: form.attr('action') + "?handler=ChangeLanguage",
    data: {
    __RequestVerificationToken: token,
    },

    success: function (data) {
                $('#name').html(@Model.name); THIS ALWAYS COMES EMPTY EVEN WHEN ITS NOT
    }

    The controller source example:

    [BindProperty]

    public string name {get; set;}

    public IActionResult OnPostChangeLanguage()

    {

    string reply = "";

    name = "Test"; HERE IS WHERE I AM ASSIGNING VALUE FOR THE PROPERTY BUT NEVER GETS BACK UPDATED TO THE AJAX CALL (ITS ALWAYS EMPTY RESPONSE).

    return new JsonResult(reply);

    }

    Sorry for the coding part I know its not pretty, but its just an example which I think would be enough to get the idea of my problem. 

    Anyways let me know if you have any ideas or questions.

    Saludos

    Sunday, July 28, 2019 8:06 PM

Answers

  • User-821857111 posted

    Try this:

    Controller:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPagesTests
    {
        public class AjaxUpdateNameModel : PageModel
        {
            [BindProperty]
            public string Name { get; set; }
            public void OnGet()
            {
            }
    
            public IActionResult OnPostChangeLanguage()
            {
                Name = "Test";
                return new JsonResult(new { name = Name });
            }
        }
    }



    Razor Page:

    @page
    @model RazorPagesTests.AjaxUpdateNameModel
    @{
    }
    <div id="name">
    
        @Model.Name
    
    </div>
    <form method="post">
        <button type="button">submit</button>
    </form>
    @section scripts{
        <script>
            $('button').on('click', function () {
                $.ajax({
                    type: 'post',
                    url: '?handler=ChangeLanguage',
                    datatype:"application/json",
                    data: {
                        __RequestVerificationToken: $('[name="__RequestVerificationToken"]').val(),
                    },
    
                    success: function (data) {
                        $('#name').html(data.name);
                    }
                });
            });
        </script>
        }

    <div></div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 8:12 PM
  • User-474980206 posted

    the razor variable @Modelname will be the value at original render, not the razor value from the ajax call. data is the razor page response (the value of the variable reply which you only set to "").

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 8:35 PM
  • User-2029935383 posted

    Ok, I think I am getting there due to your responses guys. What if I have to return multiple values some of which are html format.

    Example:

    IActionResult part:

    name = "Johnny"; // Bind property

    content = "<br /><br /><b>Test html code here</b>"; // html content

    color = "red"; // another bind property

    return new JsonResult(name + content + color); ????

    Whats going on in the ajax part???

    Thanks

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 9:35 PM
  • User711641945 posted

    Hi Stoyan,

    By using Mike's code could also return multiple values.

    [BindProperty]
    public string Name { get; set; }
    public string Color { get; set; }
    public string content { get; set; }
    public void OnGet()
    {
    }
    public IActionResult OnPostChangeLanguage()
       {
           Name = "Test";
           content = "<br/><br/><b>Test html code here</b>";
           Color = "Red";
           return new JsonResult(new { name=Name,color=Color,Content= content});
       }
    @page
    @model CreateModel
    <div id="name">@Model.Name</div>
    <div id="color">@Model.Color</div>
    <div id="content">@Model.content</div>
    <form method="post">
        <button type="button">submit</button>
    </form>
    @section scripts{
        <script>
            $('button').on('click', function () {
                $.ajax({
                    type: 'post',
                    url: '?handler=ChangeLanguage',
                    datatype: "application/json",
                    data: {
                        __RequestVerificationToken: $('[name="__RequestVerificationToken"]').val(),
                    },
                    success: function (data) {
                        $('#name').html(data.name);       
                        $('#color').html(data.color);
                        $('#content').html(data.content)
                    }
                });
            });
        </script>
    }

    Best Regards,

    Rena

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 9:46 AM
  • User-2029935383 posted

    Ok, finally works. Here's how.

    The IActionResult returns this:

    string reply = "[";

    reply += "{\"status\":\"true\", " +
    "\"content\":\"" + HttpUtility.JavaScriptStringEncode("<html>blabla</html>") + "\", " +
    "\"name\":\"" + "John" + "\"}";

    reply += "]";

    return new JsonResult(reply);

    Thank in the jquery

    success: function (data) {
            if (data !== "" && data !== "[]") {
                  $.each(JSON.parse(data), function (index, obj) {
                       if ('true' == obj.status) {

                               console.log(obj.name);

                               console.log(obj.content);

                         }

                 }

     }

    Hopefully helps to others in the same "boat".

    If some has better solution, your voice is welcome.

    Saludos

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 3:34 PM

All replies

  • User-821857111 posted

    Try this:

    Controller:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPagesTests
    {
        public class AjaxUpdateNameModel : PageModel
        {
            [BindProperty]
            public string Name { get; set; }
            public void OnGet()
            {
            }
    
            public IActionResult OnPostChangeLanguage()
            {
                Name = "Test";
                return new JsonResult(new { name = Name });
            }
        }
    }



    Razor Page:

    @page
    @model RazorPagesTests.AjaxUpdateNameModel
    @{
    }
    <div id="name">
    
        @Model.Name
    
    </div>
    <form method="post">
        <button type="button">submit</button>
    </form>
    @section scripts{
        <script>
            $('button').on('click', function () {
                $.ajax({
                    type: 'post',
                    url: '?handler=ChangeLanguage',
                    datatype:"application/json",
                    data: {
                        __RequestVerificationToken: $('[name="__RequestVerificationToken"]').val(),
                    },
    
                    success: function (data) {
                        $('#name').html(data.name);
                    }
                });
            });
        </script>
        }

    <div></div>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 8:12 PM
  • User-474980206 posted

    the razor variable @Modelname will be the value at original render, not the razor value from the ajax call. data is the razor page response (the value of the variable reply which you only set to "").

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 8:35 PM
  • User-2029935383 posted

    Ok, I think I am getting there due to your responses guys. What if I have to return multiple values some of which are html format.

    Example:

    IActionResult part:

    name = "Johnny"; // Bind property

    content = "<br /><br /><b>Test html code here</b>"; // html content

    color = "red"; // another bind property

    return new JsonResult(name + content + color); ????

    Whats going on in the ajax part???

    Thanks

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 28, 2019 9:35 PM
  • User711641945 posted

    Hi Stoyan,

    By using Mike's code could also return multiple values.

    [BindProperty]
    public string Name { get; set; }
    public string Color { get; set; }
    public string content { get; set; }
    public void OnGet()
    {
    }
    public IActionResult OnPostChangeLanguage()
       {
           Name = "Test";
           content = "<br/><br/><b>Test html code here</b>";
           Color = "Red";
           return new JsonResult(new { name=Name,color=Color,Content= content});
       }
    @page
    @model CreateModel
    <div id="name">@Model.Name</div>
    <div id="color">@Model.Color</div>
    <div id="content">@Model.content</div>
    <form method="post">
        <button type="button">submit</button>
    </form>
    @section scripts{
        <script>
            $('button').on('click', function () {
                $.ajax({
                    type: 'post',
                    url: '?handler=ChangeLanguage',
                    datatype: "application/json",
                    data: {
                        __RequestVerificationToken: $('[name="__RequestVerificationToken"]').val(),
                    },
                    success: function (data) {
                        $('#name').html(data.name);       
                        $('#color').html(data.color);
                        $('#content').html(data.content)
                    }
                });
            });
        </script>
    }

    Best Regards,

    Rena

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 9:46 AM
  • User-2029935383 posted

    Ok, finally works. Here's how.

    The IActionResult returns this:

    string reply = "[";

    reply += "{\"status\":\"true\", " +
    "\"content\":\"" + HttpUtility.JavaScriptStringEncode("<html>blabla</html>") + "\", " +
    "\"name\":\"" + "John" + "\"}";

    reply += "]";

    return new JsonResult(reply);

    Thank in the jquery

    success: function (data) {
            if (data !== "" && data !== "[]") {
                  $.each(JSON.parse(data), function (index, obj) {
                       if ('true' == obj.status) {

                               console.log(obj.name);

                               console.log(obj.content);

                         }

                 }

     }

    Hopefully helps to others in the same "boat".

    If some has better solution, your voice is welcome.

    Saludos

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 3:34 PM
  • User-821857111 posted

    string reply = "[";

    reply += "{\"status\":\"true\", " +
    "\"content\":\"" + HttpUtility.JavaScriptStringEncode("<html>blabla</html>") + "\", " +
    "\"name\":\"" + "John" + "\"}";

    reply += "]";

    You can get yourself in a bit of a mess trying to build "JSON" like that. Just let the JsonResult do it for you by constructing an anonymous type and passing it in:

    var reply = new{status = "true", content = "<html>blabla</html>", name = "John"}; 
    return new JsonResult(reply);

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types

    Monday, July 29, 2019 7:17 PM