首页 文章

MVC - 模型 - 视图和控制器的角色

提问于
浏览
0

以下是我的应用程序架构 . 我对是否理解MVC是否正确感到困惑?我的建筑是对还是不对?

视图 - 与用户交互,它具有HTML部分,在提交它称为控制器的表单上

控制器 - 它检查添加的信息是否有效? (不是数据库的观点 . 它只是检查天气是否填充了所有必填字段?)决定调用哪个模型 .

模型 - 它包含视图类 . 还有一些方法,比如添加,修改或删除来处理数据库 .

这是正确的还是犯了一些错误?以下是我的代码示例

控制器:

public ActionResult AddCustomer(CustomerModel model)
        {
            if (ModelState.IsValid)
            {
                model.AddCustomer();
                return RedirectToAction("Index", "Home");
            }
            return (View("AddCustomer",model));
        } 

 Model: 

 public class AddBookModel
    {
        [Required(ErrorMessage = "The ISBN is required.")]
        [DisplayName("ISBN")]
        public String ISBN { get; set; } 

     [DisplayName("Title")]
    [Required(ErrorMessage = "The Title is required.")]
    public String Title { get; set; }

    [Required(ErrorMessage = "The Publisher is required.")]
    [DisplayName("Publisher")]
    public String Publisher { get; set; }

    public void AddBook()
    {
        using (BBBDataContext DCBook = new BBBDataContext())
        {
            Book tableBook = new Book()
            {
                ISBN = this.ISBN,
                Title = this.Title,
                Publisher = this.Publisher,
            }
          DCBook.Books.InsertOnSubmit(tableBook);
          DCBook.SubmitChanges(); 
        }
     }
 

 View: 

        <% using (Html.BeginForm()) {%>
    <%= Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Insert Book Record</legend>
        <table id="displayform" cellspacing="0" cellpadding="5">
        <colgroup>
            <col span="1" style="text-align:right" />
            <col span="2" style="text-align:left" />
        </colgroup>
        <tr>
            <td class="editor-label">
                <%= Html.LabelFor(model => model.ISBN) %>
            </td>
            <td class="editor-field">
                <%= Html.TextBoxFor(model => model.ISBN) %>
                <%= Html.ValidationMessageFor(model => model.ISBN) %>
            </td>
        </tr>
        <tr>
            <td class="editor-label">
                <%= Html.LabelFor(model => model.Title) %>
            </td>
            <td class="editor-field">
                <%= Html.TextBoxFor(model => model.Title) %>
                <%= Html.ValidationMessageFor(model => model.Title) %>
            </td>
        </tr>

1 回答

  • 0

    您对MVC的理解很好 . 视图仅包含将显示的可视元素,并且不包含任何逻辑代码 . 控制器正在监听视图的事件(mouseClick,lostfocus ......),与模型交互,进行验证......模型包含您的业务类,并与数据库和其他外部服务进行交互 .

相关问题