Posts

....
Technical Blog for .NET Developers ©

Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Monday, January 2, 2017

MVC4 Ajax Forms

ASP.NET MVC 4 includes Ajax functionalities based on jQuery javascript library. Most of the Ajax features in the framework build on or extend features in jQuery

In this post we will implement an asynchronous request form with validation

This is the Chemical model in our Application

 
    public class ChemicalElement
    {
        public int IdElement { get; set; }

        [DisplayName("Name")]
        [Required]
        public string Name { get; set; }

        [DisplayName("Latin name")]
        [Required]
        public string LatinName { get; set; }

        [DisplayName("Symbol")]
        [Required]
        [RegularExpression(@"\b[a-zA-Z]{1,3}\b")]
        public string Symbol { get; set; }
    }
        


We have imported the next SQL schema (table and stored procedure)



The code to release the search of chemical elements is the next


    public PartialViewResult SearchChemicalElements(string search)
    {
        var elementsModel = SearchElementsModel(search);

        return PartialView("Elements", elementsModel);
    }

    private IEnumerable<ChemicalElement> SearchElementsModel(string search)
    {
        var allElements = Elements.SearchElements(search);

        return allElements;
    }
        


And in the Elements class the implementation of the SearchElement method is this

   
	public static IEnumerable<ChemicalElement> SearchElements(string search)
    {
        using (CHEMICALSEntities context = new CHEMICALSEntities())
        {
            ObjectResult<SearchElementsBySymbol_Result> matchElements =
                context.SearchElementsBySymbol("%" + search + "%");

            foreach (var element in matchElements)
                yield return new ChemicalElement()
                {
                    IdElement = element.IdElement,
                    Name = element.Name,
                    LatinName = element.LatinName,
                    Symbol = element.Symbol
                };
        }
    }
        


The code in the View to make the process work asynchronously, is the next


@using (Ajax.BeginForm("SearchChemicalElements", "Chemical", new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "GET",
        LoadingElementId = "preloader",
        UpdateTargetId = "searchResults",
    }))
        


This code renders an html form with the next marks



The information about how to perform the AJAX request is contained in the DOM, and it is released by the jquery.unobtrusive-ajax.js code

The PartialView for Elements is strongly typed and renders a table in a loop for each element



The validation rules are specified in the model, so the code in the view

 
@Html.TextBoxFor(m => m.Symbol, new { Name = "search"})


will renders the information into these data dash attributes


data-val="true" 
data-val-regex="The field Symbol must match the regular expression '\b[a-zA-Z]{1,3}\b'." 
data-val-regex-pattern="\b[a-zA-Z]{1,3}\b" 
data-val-required="The field Symbol is required." 
id="Symbol" name="search"
    


The Ajax request, and validation are implemented inside the jQuery scripts

  
  @section scripts {
    <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}    


Thursday, February 28, 2013

Send and Retrieve Json data

When we develop web applications and we are adding Ajax functionality, it's a best practice using js libraries that implement code for cross-browsing and encapsulate the callings in a clear code way, such as jQuery, instead of using raw Ajax

In this post we have a web site making an async call to the server, the process continues querying a database and returning the response to the client side in json format, so the whole circuit of the process will be the next



The code in the server-side looks like this

     
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static JsonResult getElement(string atomicSymbol)
{
    using (SqlConnection connection = new SqlConnection
    (ConfigurationManager.ConnectionStrings["chemical_bd"].ConnectionString))
    {
        try
        {
            connection.Open();

            SqlCommand proc = new SqlCommand("K_SELECT_ELEMENT", connection);
            proc.CommandType = System.Data.CommandType.StoredProcedure;

            SqlParameter p_ASymbol = new SqlParameter("@asymbol", 
              System.Data.SqlDbType.VarChar, 3);
            p_ASymbol.Value = atomicSymbol;
            p_ASymbol.Direction = System.Data.ParameterDirection.Input;

            SqlParameter p_Name = new SqlParameter("@name",  
              System.Data.SqlDbType.VarChar, 20);
            p_Name.Direction = System.Data.ParameterDirection.Output;

            SqlParameter p_LatinName = new SqlParameter("@latin_name", 
              System.Data.SqlDbType.VarChar, 20);
            p_LatinName.Direction = System.Data.ParameterDirection.Output;

            proc.Parameters.AddRange(new SqlParameter[] { p_ASymbol, p_Name, p_LatinName });

            proc.ExecuteNonQuery();

            Chemical element = new Chemical()
            {
                name = p_Name.Value.ToString(),
                latin_name = p_LatinName.Value.ToString()
            };

            return new JsonResult() { Data = element };
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

Notice that the method which processes the request is defined as static. The class JsonResponse is defined in System.Web.Mvc namespace

The calling code in the client-side has the next structure

     
function getElement(atomicSymbol) {

    var jsonData = new Object();
    jsonData.atomicSymbol = atomicSymbol;

    var jsonString = JSON.stringify(jsonData);

    $.ajax({
        url: "callprocedure.aspx/getElement",
        type: "POST",
        data: jsonString,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {

            var element = response.d.Data;
            $('#lblResult').text(element.name + " : " + element.latin_name);
        },
        error: function (result) {
            alert('ERROR: ' + result.status + ' ' + result.statusText);
        }
    });   
}

The result with a correct execution is the next




<METHOD SOFTWARE © 2013>