Create model name PersonDetails.cs
using System.Collections.Generic;
namespace MVCJsonAjax.Models
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public List< Address > Addresses { get; set; }
}
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
}
Create Controller - SaveController.cs
using System.Web.Mvc;
using MVCJsonAjax.Models;
namespace MVCJsonAjax.Controllers
{
public class SaveController : Controller
{
//
// GET: /Save/
[ActionName("SaveData"),HttpGet]
public ActionResult SaveData()
{
return View();
}
[ActionName("SaveData"), HttpPost]
public JsonResult SaveData(Person objPerson,Address objAddress)
{
JsonResult result = new JsonResult();
// Save logic - save person and address details
result.Data = "Saved Successfully";
return result;
}
}
}
Create View for ActionResult SaveData()
@using MVCJsonAjax.Models
@{
ViewBag.Title = "SaveData";
}
< h2 >
Save Data< /h2 >
< div>
< div id="message" >
< /div>
< /div >
< script type =" text/javascript ">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var Person =
{
FirstName: $('#Item1_FirstName').val(),
LastName: $('#Item1_LastName').val()
};
var Address =
{
Line1: $('#Item2_Line1').val(),
Line2: $('#Item2_Line2').val(),
ZipCode: $('#Item2_ZipCode').val(),
City: $('#Item2_City').val(),
State: $('#Item2_State').val(),
Country: $('#Item2_Country').val()
};
var obj = { "Per": Person, "Add": Address};
$.ajax({
url: '/Save/SaveData',
type: "POST",
data:JSON.stringify({objPerson: Person ,objAddress: Address }),
cache: false,
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function (result) {
$('#message').html(result).fadeIn();
}
});
return false;
});
});
@model Tuple< Person, Address >
@using ( Html.BeginForm() )
{
< table >
< tr >
< td >
@Html.LabelFor(m => m.Item1.FirstName)
@Html.TextBoxFor(m => m.Item1.FirstName)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item1.LastName)
@Html.TextBoxFor(m => m.Item1.LastName)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item2.Line1)
@Html.TextBoxFor(m => m.Item2.Line1)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item2.Line2)
@Html.TextBoxFor(m => m.Item2.Line2)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item2.ZipCode)
@Html.TextBoxFor(m => m.Item2.ZipCode)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item2.City)
@Html.TextBoxFor(m => m.Item2.City)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item2.State)
@Html.TextBoxFor(m => m.Item2.State)
< /td >
< /tr >
< tr >
< td >
@Html.LabelFor(m => m.Item2.Country)
@Html.TextBoxFor(m => m.Item2.Country)
< /td >
< /tr >
< tr >
< td >
< input type="submit" value="Submit" id="btnSubmit" / >
< /td >
< /tr >
< /table >
}
No comments:
Post a Comment
Comments Welcome