1.在Models中添加如下代码
public class Appointment
{
public string ClientName { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
public bool TermsAccepted { get; set; }
}
2.在Controllers中添加如下代码
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(new Appointment());
}
[HttpPost]
public ActionResult Index(Appointment app)
{
if (Request.IsAjaxRequest())
{
return Json(new
{
ClientName = app.ClientName,
Date = app.Date.ToShortDateString(),
TermAccepted = app.TermsAccepted
});
}
else
{
return View();
}
}
}
3.添加视图页面
@model Test.Models.Appointment
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function (e) {
e.preventDefault();
var appointment = {
ClientName: $('#ClientName').val(),
Date: $('#Date').val(),
TermsAccepted: $('#TermsAccepted').is(':checked')
};
$.ajax({
url: '@Url.Action("Index")',
type: 'POST',
data: JSON.stringify(appointment),
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#clienttarget').text(data.ClientName);
$('#datetarget').text(data.Date);
$('#termstarget').text(data.TermsAccepted);
$('#results').show();
},
});
});
});
</script>
<h4>Create Appointment</h4>
@using (Html.BeginForm()) {
@Html.EditorForModel()
<input type="submit" value="Submit" />
}
<div id="results" style="display:none">
Here is the appointment you created:
<p>ClientName: <span id="clienttarget"/></p>
<p>Date: <span id="datetarget" /></p>
<p>Terms Accepted: <span id="termstarget" /></p>
</div>