ASP.NET MVC 表单提交
实现新增数据
1.这里我们还采用上一篇做过的Blog示例(在后面的文章中,我将一直使用该示例),在这之前,先修改一下上次示例中的BlogRepository,为其增加一个Add方法:
public void Add(Post post)
{
BlogDataContext db = new BlogDataContext();
db.Posts.InsertOnSubmit(post);
db.SubmitChanges();
}2.在Index视图中添加一个可以转向新建Post页面的链接,使用ActionLink()方法:
<h2>ASP.NET MVC Framework Sample</h2>
<hr />
<%=Html.ActionLink("Home", new { action="Index"})%> |
<%=Html.ActionLink("New Post", new { action="New"})%>
<div>
<%foreach (Post post in ViewData)
{ %>
<div class="postitem">
<strong>Title</strong>:<%=Html.Encode(post.Title) %></br>
<strong>Author</strong>:<%=Html.Encode(post.Author) %></br>
<strong>PubDate</strong>:<%=Html.Encode(post.PubDate.ToShortDateString()) %></br>
<strong>Content</strong>:<%=Html.Encode(post.Description) %></br>
</div><br />
<% } %>
</div>在上面的代码中,第四行我们添加了New Post超链接,并指定该链接的action为New,这里我们也可以通过action名称来指定:
<h2>ASP.NET MVC Framework Sample</h2>
<hr />
<%=Html.ActionLink("Home", "Index")%> |
<%=Html.ActionLink("New Post", "New")%>
<div>
<%foreach (Post post in ViewData)
{ %>
<div class="postitem">
<strong>Title</strong>:<%=Html.Encode(post.Title) %></br>
<strong>Author</strong>:<%=Html.Encode(post.Author) %></br>
<strong>PubDate</strong>:<%=Html.Encode(post.PubDate.ToShortDateString()) %></br>
<strong>Content</strong>:<%=Html.Encode(post.Description) %></br>
</div><br />
<% } %>
</div>3.编写控制器中的New action代码,这里代码非常简单,因为我们只需要转向新建Post视图就可以了,并不需要其他的操作:
[ControllerAction]
public void New()
{
//转向新页面
RenderView("New");
}4.编写New视图,在这里我们将提供一些表单,供用户输入数据,编写HTML代码如下:
<h2>New Post</h2>
<hr />
<div class="postitem">
Title:<input id="title" name="title" type="text" /><br /><br />
Author:<input id="author" name="author" type="text" /><br /><br />
Content:<textarea id="description" name="description" cols="40" rows="5"></textarea><br /><br />
<input type="submit" value="Save" />
</div>接下来添加一个HTML的form元素,并指定它的action为我们要增加新的Post的action,这里假定为Add,并且指定method为Post,最终我们完成的代码应该看起来如下所示:<h2>New Post</h2>
<hr />
<div class="postitem">
<form action="Add" method="post">
1.这里我们还采用上一篇做过的Blog示例(在后面的文章中,我将一直使用该示例),在这之前,先修改一下上次示例中的BlogRepository,为其增加一个Add方法:
public void Add(Post post)
{
}2.在Index视图中添加一个可以转向新建Post页面的链接,使用ActionLink()方法:
<h2>ASP.NET MVC Framework Sample</h2>
<hr />
<%=Html.ActionLink("Home", new { action="Index"})%> |
<%=Html.ActionLink("New Post", new { action="New"})%>
<div>
</div>在上面的代码中,第四行我们添加了New Post超链接,并指定该链接的action为New,这里我们也可以通过action名称来指定:
<h2>ASP.NET MVC Framework Sample</h2>
<hr />
<%=Html.ActionLink("Home", "Index")%> |
<%=Html.ActionLink("New Post", "New")%>
<div>
</div>3.编写控制器中的New action代码,这里代码非常简单,因为我们只需要转向新建Post视图就可以了,并不需要其他的操作:
[ControllerAction]
public void New()
{
}4.编写New视图,在这里我们将提供一些表单,供用户输入数据,编写HTML代码如下:
<h2>New Post</h2>
<hr />
<div class="postitem">
</div>接下来添加一个HTML的form元素,并指定它的action为我们要增加新的Post的action,这里假定为Add,并且指定method为Post,最终我们完成的代码应该看起来如下所示:<h2>New Post</h2>
<hr />
<div class="postitem">
