访问的ViewData中的Ajax请求

访问的ViewData中的Ajax请求

本文介绍了MVC 3剃须刀 - 访问的ViewData中的Ajax请求(jQuery的,JavaScript的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一些code,用户可以检查用户名已经存在于数据库提交表单前。这对onkeyup事件处理程序,该取值从文本框并将它传递给一个Ajax请求这就要求我的ActionResult方法用字符串参数的工作方式。我的SQL逻辑的作品没关系,我收到一个值,说已经存在。

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.

我的问题是从我的控制,我想返回值。在我的jQuery的Ajax请求的成功部分我想访问我的计算机[索引名],但我的提醒显示一个空字符串。

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#控制器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.

推荐答案

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

            }
        });

这篇关于MVC 3剃须刀 - 访问的ViewData中的Ajax请求(jQuery的,JavaScript的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 21:28