MVC 3 Razor - Access ViewData in Ajax Request (Jquery, JavaScript)

懵懂的女人 提交于 2019-12-12 18:33:10

问题


I am writing some code where the user can check if a username already exists in the database before submitting the form. This works by on onkeyup event handler which takes the value from the textbox and passing it to an ajax request which calls my ActionResult method with a string parameter. My SQL logic works okay, I recieve a value which says already exists or not.

The problem I have is from my Controller, I want to return the value. In the success part of my Jquery Ajax request I am trying to access my ViewData["index name"] but my alert shows an empty string.

Javascript code :

function searchUsername() {
     var filters = getFilterVals();
     $.ajax({
         url: '@Url.Action("UsernameSearch", "UserManager")',
         type: "POST",
         async: true,
         dataType: "text",
         data: "username=" + filters.username,
         success: function () {
             var str = '@ViewData["UserName"]';
             alert(str);
             $('#txtUsernameExists').val(str);
             configureGui();
             jQueryTableStyling();
         },
         error: function (data) {

         }
     });
}

function getFilterVals() {
     filters = new Object();
     filters.username = $('#createuser-usernamesearch #user_name').val();
     return filters;
}

C# controller code :

public ActionResult UsernameSearch(string username)
{
    string output = DAL.usernameSearch(username);
    ViewData["Username"] = output;
    return PartialView("~/Views/Partial/_txtUsernameSearch.cshtml");
}

What am I doing wrong? Any suggestions are welcome.


回答1:


ASP.NET:

public JsonResult UsernameSearch(string username)
{
            string output = DAL.usernameSearch(username);

            return Json(new
            {
                Html = PartialView("~/Views/Partial/_txtUsernameSearch.cshtml"),
                Username = output
            });
}

JS:

$.ajax({
            url: '@Url.Action("UsernameSearch", "UserManager")',
            type: "POST",
            async: true,
            dataType: "json",
            data: "username=" + filters.username,
            success: function (data) {

                var html = data.Html;
                var str = data.Username;
                alert(str);

                $('#txtUsernameExists').val(str);
                configureGui();
                jQueryTableStyling();
            },
            error: function (data) {

            }
        });



回答2:


Try this:

Change:

ViewData["Username"] = output;

For this:

ViewData["UserName"] = output;


来源:https://stackoverflow.com/questions/13803565/mvc-3-razor-access-viewdata-in-ajax-request-jquery-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!