12 October 2015

Posting data in MVC example

Here is the view

 <!doctype html>  
 @{  
   ViewBag.Title = "Index";  
   Layout = null;  
 }  
 <html lang="en">  
 <head>  
   <meta charset="utf-8">  
   <title>Save City</title>  
   <link href="~/Scripts/jquery-ui.css" rel="stylesheet">  
   <script src="~/Scripts/jquery-1.10.2.js"></script>  
   <script src="~/Scripts/jquery-ui.js"></script>  
 </head>  
 <body>  
   <label for="country">Select your country: </label>  
   <input id="country">  
   <br />  
   <label for="city">Select your city: </label>  
   <input id="city">  
   <br />  
   <input type="button" name="btnclick" id="btnclick" value="click" />  
   <div id="divAlert"> </div>  
   <script>  
     $('#btnclick').click(function () {  
     $.ajax({  
       url: '@Url.Action("InsertCity", "Home")',  
       type: 'POST',  
       data: JSON.stringify({ countryName: $('#country').val(), city: $('#city').val() }),  
       contentType: 'application/json; charset=utf-8',  
       dataType: 'json',  
       success: function (rdata) {  
         $('#divAlert').html(rdata.result);  
       },  
       error: function (req, status, error) {  
         alert("R: " + req + " S: " + status + " E: " + error);  
       }  
     });  
   })  
   </script>  
 </body>  
 </html>  


Here is the controller function

     [HttpPost]  
     public JsonResult InsertCity(string countryName, string city)  
     {  
       string cnnStr = ConfigurationManager.ConnectionStrings["GraphConnection"].ConnectionString;  
       SqlConnection dcnn = new SqlConnection(cnnStr);  
       dcnn.Open();  
       SqlCommand dcmd = new SqlCommand("dbo.InsertCity", dcnn);  
       dcmd.CommandType = CommandType.StoredProcedure;  
       dcmd.Parameters.AddWithValue("@CountryName", countryName);  
       dcmd.Parameters.AddWithValue("@City", city);  
       SqlParameter dRet = new SqlParameter("@ReturnValue", SqlDbType.Int, 4);  
       dRet.Direction = ParameterDirection.ReturnValue;  
       dcmd.Parameters.Add(dRet);  
       dcmd.ExecuteNonQuery();  
       int iRet = Utility.ConvertToInt(dRet.Value);  
       return Json(new { result = "successfully submitted" }, JsonRequestBehavior.AllowGet);  
     }  



No comments:

Post a Comment