N
N
Nik Faraday2022-01-11 00:35:58
ASP.NET
Nik Faraday, 2022-01-11 00:35:58

Why does ViewData return an empty string?

Hello!

When registering, I need to pass the appropriate value, or rather, the result, after processing the data during registration, and return the appropriate string for display on the page. I do this using ViewData but it returns me an empty string. When I try to use the ToString() method, it tells me that my ViewData object is null and I don't understand what the problem is.

Controller code:

[IgnoreAntiforgeryToken]
        [HttpPost]
        public async Task<IActionResult> Registration([FromBody]UserEntryViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                ViewData["ResponseMessage"] = "Invalid data";
                return BadRequest();
            }
            
            UserEntity userEntity = new UserEntity()
            {
                Email = viewModel.Email,
                Login = viewModel.Login,
                Name = viewModel.Name,
                Password = viewModel.Password,
                Type = UserType.Client,
            };

            var user = _userService.GetByEmail(userEntity.Email);
            if (user.Count > 0)
            {
                ViewData["ResponseMessage"] = "Was created";
                return BadRequest();
            }

            _userService.Create(userEntity);
            ViewData["ResponseMessage"] = "Created successfuly";

            return Json(new { success = true });
        }


Presentation code:

@using SteamEmart.Web.Models;
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model UserEntryViewModel

<h1>@ViewData["ResponseMessage"]</h1>
<div style="margin-left: 40%; margin-right: 40%">
    @Html.ValidationSummary(false, null, new { @class = "text-danger"})
    <form id="userData">

        <h3>Name</h3>
        <input id="name" type="text" placeholder="Vasia"/> <br /> <br />

        <h3>Login</h3>
        <input id="login" type="text" placeholder="Vasiliy"/> <br /> <br />

        <h3>Email</h3>
        <input id="email" type="email" placeholder="[email protected]"/>

        <h3>Password</h3>
        <input id="password" type="password" placeholder="Secret"/> <br /> <br />

        <input type="button" id="submitBtn" style="width: 100px"/>
     </form>
</div>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
    $("#submitBtn").bind('click', () => {

        var formData = {
            name: $('#name').val(),
            login: $('#login').val(),
            email: $('#email').val(),
            Password: $('#password').val(),
        }

            $.ajax({
            url: '@Url.Action("Registration", "User")',
            type: 'POST',
            data: JSON.stringify(formData),
            contentType: "application/json; charset=utf-8",
            dataType: 'JSON',
            success: (message) => {
                $('#name').val("");
                $('#login').val("");
                $('#email').val("");
                $('#password').val("");
                alert(@ViewData["ResponseMessage"]);
            },
            error: () => {
                alert(@ViewData["ResponseMessage"]);
            }
        });
    });
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nik Faraday, 2022-01-11
@NikFaraday

Answer: html markup is generated on the server. When the markup is received, the HttpGet method is processed, and when data is sent, the HttpPost method is processed. Since I use Ajax, my page is not reloaded and, accordingly, the markup is not regenerated, which means that the value of ViewBag, ViewData, and so on does not change after sending data to the server via Ajax. Accordingly, the ViewBad and ViewData values ​​have standard values, i.e. null.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question