您可以随心所欲地进行操作,但您将打破“关注点分离”的概念。控制器应该只关心它将调用或执行哪个视图或哪个操作。模型应该只用于你的数据的结构,它通常类似于你的数据库属性的外观。简而言之,你的模型(类模型)应该有最少的思考。例如,您有一个名为 Person 的表,其列为 IDPerson、FirstName、LastName。您的模型应该与此类似:
public class Person {
public IdPerson {get;set;}
public FirstName {get;set;}
public LastName {get;set;}
}
假设您有一个视图可以显示一个人的详细信息,这可能是某物
像这样:
public class PersonController : Controller
public ActionResult GetPerson(int IdPerson){
PersonBusinessLogic pbl = new PersonBusinessLogic();
Person p = pbl.GetPersonFromDatabase(id); //To add more consistency, the data access is on a separate class for better maintenance and to emphasize "Separation of Concerns"
ViewResult vr = new ViewResult()
{
ViewName = this.View,//This is where you assign the page if you have other pages for this action
ViewData = new ViewDataDictionary(ViewData)
{
Model = p
}
};
return vr;
}
为了你的原油:
[HttpPost]
public ActionResult CreatePerson(Person p)
{
try
{
if (ModelState.IsValid)
{
PersonBusinessLogic pbl = new PersonBusinessLogic();
pbl.CreatePersonToDatabase(p);
return RedirectToAction("Index", "Home");
}
}
catch(Exception ex){
ModelState.AddModelError("",ex.Message);
}
return View(p);
}
[HttpPost]
public ActionResult UpdatePerson(Person p)
{
try
{
if (ModelState.IsValid)
{
PersonBusinessLogic pbl = new PersonBusinessLogic();
pbl.UpdatePersonToDatabase(p);
return RedirectToAction("Index", "Home");
}
}
catch(Exception ex){
ModelState.AddModelError("",ex.Message);
}
return View(p);
}
[HttpPost]
public ActionResult DeletePerson(Person p)
{
try
{
if (ModelState.IsValid)
{
PersonBusinessLogic pbl = new PersonBusinessLogic();
pbl.DeletePersonByIDFromDatabase(p.IdPerson);
return RedirectToAction("Index", "Home");
}
}
catch(Exception ex){
ModelState.AddModelError("",ex.Message);
}
return View(p);
}
为了给你一个更好的想法,找到一些关于如何将 MVC 作为一个概念得到极大应用的文章,那么你将非常欣赏学习过程。