第 1 步:为简单兴趣创建模型
namespace CalculateSimpleInterest.Models
{
public class SimpleInterestModel
{
public decimal Amount { get; set; }
public decimal Rate { get; set; }
public int Year { get; set; }
}
}
第 2 步:创建一个在 UI 上呈现视图的操作方法
我们正在传递一个空模型以绑定到视图。
public ActionResult SimpleInterest()
{
SimpleInterestModel model = new SimpleInterestModel();
return View(model);
}
第 3 步:创建强类型视图
@model CalculateSimpleInterest.Models.SimpleInterestModel
@{
ViewBag.Title = "SimpleInterest";
}
<h2>Calulate Simple Interest</h2>
@using (Ajax.BeginForm("CalculateSimpleInterestResult","CalculateSimpleInterest",
new AjaxOptions { UpdateTargetId = "divInterestDeatils" }))
{
<fieldset>
<legend>Calulate Simple Interest</legend>
<div id="divInterestDeatils"></div>
<div class="editor-label">
@Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Amount)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Rate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Year)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Year)
</div>
<p>
<input type="submit" value="Calculate" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
第 4 步:创建一个处理 POST 请求并处理数据的操作方法
在 action 方法中,我们传递一个模型作为参数。该模型具有 UI 输入字段数据。这里我们不需要解析,也不需要编写额外的代码。
[HttpPost]
public ActionResult CalculateSimpleInterestResult(SimpleInterestModel model)
{
decimal simpleInteresrt = (model.Amount*model.Year*model.Rate)/100;
StringBuilder sbInterest = new StringBuilder();
sbInterest.Append("<b>Amount :</b> " + model.Amount+"<br/>");
sbInterest.Append("<b>Rate :</b> " + model.Rate + "<br/>");
sbInterest.Append("<b>Time(year) :</b> " + model.Year + "<br/>");
sbInterest.Append("<b>Interest :</b> " + simpleInteresrt);
return Content(sbInterest.ToString());
}