Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an ajax call in MVC4

I am new to MVC4. I have to create a login name validation. After writing a string, when we exit from the textbox, it should display whether it is available or not.

The View Code is:

@{
    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>
}

Now in place of alert("a"), I will have to call an action. That action will contains the database check.

Controller Code:

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

Now my question is how to call this SearchUser() action and display it into the same page when we go out from the textbox1.

Any suggestion please.

like image 979
Arindam Rudra Avatar asked Jan 09 '13 05:01

Arindam Rudra


People also ask

Can we use AJAX in MVC?

The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.

How does AJAX call work?

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

What is AJAX in JavaScript with example?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.


1 Answers

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 method

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);            
        }
    }
}
  • I would recommend using an ORM (Entity Framework or Nhibernate)
  • Beware SQL injection even if you're using a stored procedure: http://www.troyhunt.com/2012/12/stored-procedures-and-orms-wont-save.html
like image 119
Gabriel Avatar answered Sep 30 '22 05:09

Gabriel