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

nick gowdy picture nick gowdy · Dec 10, 2012 · Viewed 8.3k times · Source

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.

Answer

Cristi Pufu picture Cristi Pufu · Dec 10, 2012

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) {

            }
        });