模型的工作是表示问题域、维护状态并提供访问和改变应用程序状态的方法。
例如,在您的网站中,如果您有上面所说的联系表格,那么您的 MVC 模式将是这样的
型号
namespace WebApplication1.Models
{
public class Contact {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Comment { get; set; }
}
}
查看(不包括所有字段)
@using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @id = "contact-form", role = "form" }))
{
@Html.ValidationSummary()
<fieldset>
<div class="form-div-1">
<label class="name">
@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "First Name *", @type = "text" })
</label>
</div>
<div class="form-div-2">
<label class="email">
@Html.TextBoxFor(m => m.Email, new { @placeholder = "Email Address *", @type = "email" })
</label>
</div>
<div class="button-wrapper">
<input type="submit" value="Send" name="submit" class="button">
</div>
</fieldset>
}
控制器
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
MailAddress from = new MailAddress(e.Email.ToString());
message.Append("First Name: " + e.FirstName + "\n");
message.Append("Email: " + e.Email + "\n");
// send email logic below
}
}
现在通过这个基本示例,您可以看到拆分逻辑的重要性和好处。
模型只是为您的数据提供了一个很好的抽象。模型可以让您思考“我的应用程序的对象如何相互关联,它们如何交互以及我如何从他们那里获取我需要的数据”。
MVC 的中心组件,模型,捕获应用程序的
就其问题域而言的行为,独立于用户
界面。模型直接管理应用程序的数据、逻辑
和规则
是的,基本上模型是大多数 MVC 应用程序中最大、最重要的层。