Asp.net MVC2.0系列文章-添加操作

点击有惊喜


创建数据模型Model

数据模型主要包括数据信息、验证规则以及业务逻辑。

创建Model的方式有多种,可以使用微软的ADO.NET Entity Data Model,也可以使用第三方工具生成实体对象,对于比较简单的实体,我们可以手工添加,此处就是手动敲上去的。

 

                                                           

Asp.net MVC2.0系列文章-添加操作

 

分析:此处定义了新闻实体对象的的一些属性,在每个Property上都存在一些注解,比如字段TitleRequiredAttribute表明Title栏位是必填字段,如果不填写会显示错误信息请输入标题!

DataTypeAttribute属性表明此字段的数据类型为文本类型,它是个枚举类型集合,如下:

 

 

Member name

Description

Custom

Represents a custom data type.

DateTime

Represents an instant in time, expressed as a date and time of day.

Date

Represents a date value.

Time

Represents a time value.

Duration

Represents a continuous time during which an object exists.

PhoneNumber

Represents a phone number value.

Currency

Represents a currency value.

Text

Represents text that is displayed.

Html

Represents an HTML file.

MultilineText

Represents multi-line text.

EmailAddress

Represents an e-mail address.

Password

Represent a password value.

Url

Represents a URL value.

ImageUrl

Represents a URL to an image.

这些类型,可以分别试试,看看最终效果什么样子的。

 

DisplayNameAttribute属性表明了此字段要文字说明。

 

创建View视图

MVC提供了生成View的向导工具,很方便的,如下图流程步骤:

我们在View文件夹下,新建一个新文件夹,命名为News

右击News文件夹,选择Add->Add  View功能菜单,出现如下界面:

Asp.net MVC2.0系列文章-添加操作

View name栏位,我可以给此视图修改名称,比如AddNews

选中Create a strongly-typed view 栏位,选择刚才定义的实体类Model,并选择View content栏位为Create操作。

其他栏位默认值就OK

最终效果如下图所示:

Asp.net MVC2.0系列文章-添加操作

单击【Add】按钮,即可添加AddNews.aspx视图成功。此文件的核心代码如下所示:

 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>

        ¬¨ª¨®??</h2>

    <% using (Html.BeginForm())

       {%>

    <%: Html.ValidationSummary(true%>

    <fieldset>

        <legend>??</legend>

        <div class="editor-label">

            <%: Html.LabelFor(model => model.Title) %>

        </div>

        <div class="editor-field">

            <%: Html.TextBoxFor(model => model.Title) %>

            <%: Html.ValidationMessageFor(model => model.Title) %>

        </div>

        <div class="editor-label">

            <%: Html.LabelFor(model => model.CreateTime) %>

        </div>

        <div class="editor-field">

            <%: Html.TextBoxFor(model => model.CreateTime, new { @class = "date"})%>

            <%: Html.ValidationMessageFor(model => model.CreateTime) %>

        </div>

        <div class="editor-label">

            <%: Html.LabelFor(model => model.Content) %>

        </div>

        <div class="editor-field">

            <%: Html.EditorFor(model => model.Content) %>

            <%: Html.ValidationMessageFor(model => model.Content) %>

        </div>

        <p>

            <input type="submit" value="¬¨ª¨®" />

        </p>

    </fieldset>

    <% } %>

    <div>

        <%: Html.ActionLink("Back to List""Index","Home"%>

    </div>

</asp:Content>


点击有惊喜
Asp.net MVC2.0系列文章-添加操作