Monday, 30 September 2013

Insert Data using Jquery in ASP.NET Mvc2

Its simple single form page which includes

-  Fullname
-  Age
-  Save Button

On Save button click , you will get message using JQUERY in ASP.NET MVC2


Models :

 [Serializable]
public class UserModels
{
  public string Name { get; set; }      
  public int Age { get; set; }
  public string message { get; set; }
}
Controller :

public ActionResult Index()
{
    return View();
}


[HttpPost]
public ActionResult Save(UserModels inputModel)
{
    string message = string.Format("Created user '{0}' in the system.", inputModel.Name);
    return Json(new UserModels { message = message });
}


Views :


 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
             $(function() {               
$("#personCreate").click(function() {
var person = getPerson();
if (person == null) {                      
alert("Specify a name please!");
return;
} // take the data and post it via json

$.post("User/Save", person, function(data) {
// get the result and do some magic with it
var message = data.Message;
$(
"#resultMessage").html(message);
});
});
});
function getPerson() {
var name =
$("#Name").val();

var age = $("#Age").val();
return (name == "") ? null : { Name: name, Age: age };
}
</script>
<h2>
Index</h2>
<div class="editor-label">
<label for="Name">
Name</label></div>
    <div class="editor-field">
<input class="text-box single-line" id="Name" name="Name" type="text" value="" />
</div>
<div class="editor-label">
<label for="Age">
Age</label></div>
<div class="editor-field">
<input class="text-box sinle-line" id="Age" name="Age" type="text" value="" />
</div>
<p>
<input type="submit" value="Save" id="personCreate" /></p>
<div>
<span id="resultMessage"></span>
</div>
</asp:Content>


I have just started MVC using JQUERY...If any correction pls suggest

 

No comments:

Post a Comment