c# - 如何在 MVC4 中进行 ajax 调用

标签 c# jquery asp.net-mvc-4

我是 MVC4 的新手。我必须创建一个登录名验证。写入一个字符串后,当我们退出文本框时,它应该显示它是否可用。

查看代码是:

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            @Html.TextBox("textbox1")
            @Html.TextBox("txtTest")
        </div>
    </section>
}
@section scripts{
    <script type="text/javascript">
        $(document).ready(function(){
            $('#textbox1').blur(function(){
                alert("a");
            });
        });
    </script>
}

现在代替alert("a"),我必须调用一个 Action 。该操作将包含数据库检查。

Controller 代码:

public class HomeController : Controller
    {
        public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }
        public ActionResult SearchUser()
        {
            string ExistsCheck;
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"].ToString());
            SqlDataAdapter da = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand();
            DataTable dt = new DataTable();
            cmd = new SqlCommand("sp_UserName_Exist_tbl_UserDetails", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", Request.Form["textbox1"]);
            da.SelectCommand = cmd;
            da.Fill(dt);
            if (dt != null && dt.Rows.Count > 0 && dt.Rows[0][0].ToString().ToLower() == "exists")
            {
                ExistsCheck = "Exists";
            }
            else
            {
                ExistsCheck = "Available";
            }
            return View();
        }
    }

现在我的问题是如何调用此 SearchUser() 操作并在我们从文本框 1 中退出时将其显示到同一页面中。

请提出任何建议。

最佳答案

JavaScript

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <table>
                <tr>
                    <td>
                        @Html.TextBox("textbox1")
                    </td>
                    <td>
                        <div id="regTitle"></div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        @Html.TextBox("txtTest")
                    </td>
                </tr>
            </table>
        </div>

    </section>
}
@section scripts{
<script type="text/javascript">
    $(document).ready(function () {
        $('#textbox1').blur(function () {
            var params = { userName: $(this).val() };
            $.ajax({
                url: "Home/SearchUser",
                type: "get",
                data: { userName: $("#textbox1").val() },
                success: function (response, textStatus, jqXHR) {
                    if (response.IsExisting) {
                        // User name is existing already, you can display a message to the user
                        $("#regTitle").html("Already Exists")
                    }
                    else {
                        // User name is not existing
                        $("#regTitle").html("Available")
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("error");
                },
                // callback handler that will be called on completion
                // which means, either on success or error
                complete: function () {
                    }
            });
        });
    });
</script>
}

Controller 方法

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc4_Ajax.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        [HttpGet]
        public ActionResult SearchUser(string userName)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["conn"].ToString());
            SqlDataAdapter da = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand();
            DataTable dt = new DataTable();
            cmd = new SqlCommand("sp_UserName_Exist_tbl_UserDetails", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", userName);
            da.SelectCommand = cmd;
            da.Fill(dt);
            var isExisting = dt != null && dt.Rows.Count > 0 && dt.Rows[0][0].ToString().ToLower() == "exists";
            return Json(new { IsExisting = isExisting }, JsonRequestBehavior.AllowGet);            
        }
    }
}

关于c# - 如何在 MVC4 中进行 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14228849/

相关文章:

c# - 用于 JQuery 日期时间选择器的 ASP.Net 包装器控件

asp.net - 有没有办法在 VS2012 捆绑中使用外部 javascript/css?

c# - MongoDB C# 驱动程序 : create document if not exists

jquery - 如何删除导航和主要内容之间多余的空白?

c# - 如何将 C# 可为空的 int 转换为 int

jquery - HTML 页面无法在 Raspberry Pi 上的 Apache 上正确呈现

c# - 在 MVC 4 中使用自定义授权

css - Bootstrap ,导航菜单下的白线,事件链接

c# - 目录.GetFiles : Show only files starting with a numeric value

c# - 重命名文件Powershell看不到