【问题标题】:MVC - Model - View and Controller 's roleMVC - 模型 - 视图和控制器的角色
【发布时间】:2012-11-08 14:52:12
【问题描述】:

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

视图 - 与用户交互,它有 HTML 部分,在提交它调用控制器的表单时

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

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

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

控制器:

 public ActionResult AddCustomer(CustomerModel 模型)
        {
            如果(模型状态。IsValid)
            {
                模型.AddCustomer();
                return RedirectToAction("Index", "Home");
            }
            return (View("AddCustomer",model));
        }

型号:

公共类 AddBookModel { [Required(ErrorMessage = "ISBN 是必需的。")] [显示名称(“ISBN”)] 公共字符串 ISBN { 获取;放; }

    [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(); 
        }
     }

查看:

       <% 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>

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 2012-02-12
      • 2013-12-06
      相关资源
      最近更新 更多