Friday, February 27, 2015

Calling MVC Server Side Function without using JQuery



I have a Web Method, which is part of my MVC controller.

       [HttpPost]        public JsonResult AddProduct(string productName, string productPrice)
        {
            JsonResult togoValue = new JsonResult();
            try
            {
                Product newProduct = new Product(productName, Convert.ToDouble(productPrice));
                if (newProduct.IsDuplicate() == false)
                {
                    newProduct.Save();
                }
                else
                {
                    throw new Exception("Product with same name and price already exists!");
                }
                togoValue = Json(InMemoryDB.GetAllRecordsinJSONFormat());
            }
            catch (Exception ex)
            {
                togoValue = Json("Error : " + ex.Message.ToString());
            }
            return togoValue;
        }


Examine the highlighted items above.  

HttpPost - This keyword mentions this method can be called only by a POST call.
JsonResult - This is the return type of the web method.
productName and productPrice - These are the input arguments of two different types.

I am calling this server side function using the following JavaScript call without using JQuery.

       function SendProducttoServer(inProdName, inProdPrice) {
            var newProduct = "productName=" + inProdName + "&productPrice=" + inProdPrice ;            var xmlhttp = new XMLHttpRequest();
            if (xmlhttp == null) {
                alert("Browser does not support XMLHttpRequest.");
            }
            else {
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        if (xmlhttp.responseText.indexOf("Error") > -1)
                        {
                            ShowUserMessage(xmlhttp.responseText);
                        }
                        else
                        {
                            ShowUserMessage("Added new record !");
                            var allRecords = JSON.parse(xmlhttp.responseText);
                            UpdateTable(allRecords);
                        }
                    }
                }
                xmlhttp.open("POST", "/Default/AddProduct", true);
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xmlhttp.send(newProduct);

            }
        }


Note the highlighted items in the above JavaScript function. This function performs a POST call and submits the arguments to the Server Side Function.

This type of calling will come in handy if the client insists not to use JQuery or other third party scripts.

Happy Coding !

Cheers
Adam

No comments:

Post a Comment

All Blogs so far ...