【问题标题】:How to make an ajax call in MVC4如何在 MVC4 中进行 ajax 调用
【发布时间】:2012-12-23 02:58:58
【问题描述】:

我是 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"),我将不得不采取行动。该操作将包含数据库检查。

控制器代码:

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() 操作并在我们从 textbox1 出去时将其显示到同一页面中。

请给点建议。

【问题讨论】:

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


    【解决方案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>
    }
    

    控制器方法

    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);            
            }
        }
    }
    

    【讨论】:

    • 加载视图时第一次触发 ajax。下次 ajax 不触发。
    • 我的 JavaScript 代码应该只替换 alert("a"); 你应该保留其他所有内容。
    • 是的,我在同一个部分用过。
    • 你不应该在你的情况下使用completecomplete 在所有情况下都会执行(成功和错误)。
    • 这种情况说明有错误,你应该使用Firebug查看HTTP响应。
    【解决方案2】:

    您正在重新发明轮子。 MVC 提供了一个接口——IClientValidatable——来完成这个。几乎所有的 MVC 表单验证都可以通过属性属性的组合来完成(即 [必需的] 服务器端和客户端与非侵入式验证)、IClientValidatable(客户端)和 IValidatable(服务器端)。这是一个完整的验证示例 - MVC3 - Custom Client-Side Validation with Unobtrusive Ajax - a Complete Example

    【讨论】:

    • 验证只是使用 AJAX 的一个例子。这是一个很好的问题和很好的答案,非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    相关资源
    最近更新 更多