2013年8月6日星期二

ASP.NET MVC 4使用技巧4:从controller到view传递information的方法

其实有三个方法用于传递information

    • 使用 strongly typed model object
    • 使用 ViewBag
    • 使用 dynamic type (using @model dynamic)

本来要用自己的例子,但是找到几个非常有趣的例子,来自于《Pro asp.net mvc 4 4th edition》,这里做一个引用。

关于strongly typed model object,请参考:

http://www.asp.net/mvc/tutorials/views/dynamic-v-strongly-typed-views

或《Pro asp.net mvc 4 4th edition》31页

 

关于ViewBag,它其实是一个dynamic object可以用于赋值。

以下代码源于《Pro asp.net mvc 4 4th edition》26页

Controller:

1 public class HomeController : Controller {
2 public ViewResult Index() {
3     int hour = DateTime.Now.Hour;
4     ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
5     return View();
6     }
7 }

View:

@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
10 <body>
11 <div>
12     @ViewBag.Greeting World (from the view)
13 </div>
14 </body>
15 </html>

 

关于用dynamic type (using @model dynamic)

以下代码子源于《Pro asp.net mvc 4 4th edition》35页

Model:

1 namespace PartyInvites.Models {
2     public class GuestResponse {
3     public string Name { get; set; }
4     public string Email { get; set; }
5     public string Phone { get; set; }
6     public bool? WillAttend { get; set; }
7     }
8 }

其中WillAttend为nullable bool,也就是它的值可以为true,false或者为null。

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartyInvites.Models;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
    public ViewResult Index() {
10         int hour = DateTime.Now.Hour;
11         ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good Afternoon";
12         return View();
13     }
14     [HttpGet]
15     public ViewResult RsvpForm() {
16         return View();   
17     }
18     [HttpPost]
19     public ViewResult RsvpForm(GuestResponse guestResponse) {
20         // TODO: Email response to the party organizer
21         return View("Thanks", guestResponse);
22     }
23 }
24 }

注意的是HttpGet attribute和HttpPost attribute,告诉method是处理get还是post。

View: RsvpForm.cshtml

@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
10 </head>
11 <body>
12 @using (Html.BeginForm()) {
13     <p>Your name: @Html.TextBoxFor(x => x.Name) </p>
14     <p>Your email: @Html.TextBoxFor(x => x.Email)</p>
15     <p>Your phone: @Html.TextBoxFor(x => x.Phone)</p>
16     <p>
17     Will you attend?
18         @Html.DropDownListFor(x => x.WillAttend, new[] {
19         new SelectListItem() {Text = "Yes, I'll be there",
20         Value = bool.TrueString},
21         new SelectListItem() {Text = "No, I can't come",Value = bool.FalseString}
22         }, "Choose an option")
23         </p>
24         <input type="submit" value="Submit RSVP" />
25     }
26 </body>
27 </html>

 

View: Thanks.cshtml

@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Thanks</title>
10 </head>
11 <body>
12 <div>
13 <h1>Thank you, @Model.Name!</h1>
14     @if (Model.WillAttend == true) {
15     @:It's great that you're coming. The drinks are already in the fridge!
16     } else {
17     @:Sorry to hear that you can't make it, but thanks for letting us know.
18     }
19 </div>
20 </body>
21 </html>

2013年8月5日星期一

ASP.NET MVC 4使用技巧记录3:Twitter.Bootstrap安装和常用HtmlHelper

1. 安装Twitter.Bootstrap(于HTML,CSS,JAVASCRIPT的简洁灵活的流行前端框架及交互组件集)

PM> install-Package Twitter.Bootstrap.Less

PM> install-package dotless

 

2. 传递Pass Data从Controller到View

A. 可以使用public ViewDataDictionary ViewData { get; set; }

譬如:

in Controller:

ViewData["info"] = "Wrong Invitation Code!";

in View:

   @ViewData["info"] 

B. 也可以使用public Object ViewBag { get; }

譬如:

in Controller:

ViewBag.Message = "Wrong Invitation Code!";

in View:

   The message is @ViewBag.Message

C. 当然也可以使用Session

in Controller:

Session["info"] = “Wrong Invitation Code!”;

in View: 

@Session["info"]

 

3. 关于model 在 razor view中

需要在View中置顶声明model type:

@model MyNamespace.Models.MyModel

"model"是小写的m -- 用来指明具体的View要呈现的Model类型。也就是declares the model。

"Model"是大写M --当我们引用一个model对象时。也就是references the instantiation of the model。

 

4. 关于常用的HtmlHelper:

在System.Web.Mvc.Html中

具体参阅:

http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper

BeginForm()

BeginRouteForm() :根据URL路由规矩。

EndForm()

譬如:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {

   @Html.AntiForgeryToken()

   @Html.ValidationSummary(true)

   <fieldset>

       <legend>Log in Form</legend>
10
11        <ol>
12
13            <li>
14
15                @Html.LabelFor(m => m.UserName)
16
17                @Html.TextBoxFor(m => m.UserName)
18
19                @Html.ValidationMessageFor(m => m.UserName)
20
21            </li>
22
23            <li>
24
25                @Html.LabelFor(m => m.Password)
26
27                @Html.PasswordFor(m => m.Password)
28
29                @Html.ValidationMessageFor(m => m.Password)
30
31            </li>
32
33        </ol>
34
35        <input type="submit" value="Log in" />
36
37    </fieldset>
38
39  }
40

 

CheckBox() , CheckBoxFor()

譬如:

@Html.CheckBox( "MyCheckBox" , true , new { id="checkbox" } )

Hidden() , HiddenFor() 某个隐藏输入域,这种类型的输入元素实际上是隐藏的。这个不可见的表单元素的 value 属性保存了一个要提交给 Web 服务器的任意字符串。如果想要提交并非用户直接输入的数据的话,就是用这种类型的元素。

譬如:

@Html.Hidden( "Hidden" , "Hidden Value")
 
Password() , PasswordFor()   

譬如:

@Html.Password ( "Password" , 123456)

RadioButton() , RadioButtonFor()

譬如:

@Html.RadioButton ( "MyRadioButton" , "RadioValue" , true)

或者:

@Html.RadioButtonFor(m =>m.Position, "0", true) Employee

@Html.RadioButtonFor(m =>m.Position, "1", false) Manager

TextBox() , TextBoxFor()

譬如:

@Html.RadioButton ( "MyTextBox" , "TextValue" new { maxlength =100 })

DropDownList() , DropDownListFor()

譬如:

@HtmlDropDownList("List" , new SelectList( new int{1, 2, 3, 4 }))

ListBox() , ListBoxFor()

譬如:

@Html.ListBox ("List" , new SelectList(new string[]{ "apple" , "banana" , "orange" ,"mango"}))

TextArea() , TextAreaFor()

譬如:

@Html.TextArea("Message", new { rows=40, columns=40 })

LabelFor()

譬如:

@Html.LabelFor(m => m.Mobile)

TextBoxFor()

譬如:

@Html.TextBoxFor(m => m.Mobile)

ActionLink():超链接

譬如:

@Html.ActionLink ( "Links Name" , "New" , "Home" )

也就是在控制器Home上执行“New”方法

RouteLink(): 根据Route产生超链接 。

譬如:

@Html.RouteLink( "NewLink" , new { controller="Home" , action="New"} )

Html.partial(),是将视图内容直接生成一个字符串并返回。

譬如:

@Html.Partial("_LoginPartial") 

@Html.Partial("NavigateBarUserControl",Model)

RenderPartial() ,想对于Html.partial()而言,RenderPartial()直接输出至当前 HttpContext,性能较好。

譬如:

@Html.RenderPartial("Path/to/my/partial/view")

ValidationMessage() , ValidationMessageFor()

譬如:

@Html.ValidationMessageFor(m => m.Password)

2013年8月4日星期日

ASP.NET MVC 4使用技巧记录2: 如何进行Migrations和使用Simplemembership

MVC4 Simplemembership可以进行权限管理,很强大,我们也可以自己扩展数据库结构,它使用几个表:
  • 用户信息表UserProfile
  • 角色表webpages_Roles
  • webpages_Membership(用于存储Membership的信息内容)
  • 权限表webpages_Permission
  • 关系表webpages_PermissionsInRoles(用于存储角色的具体权限)
1. 建一个新的C# MVC4 Web Application在VS 2012,使用Internet Application的Project Template
2. 如果使用 Machine\SQLExpress,请确定Connection String in the web.config
在Web.Config中,在其“System.Web” 部分中加入:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
  <providers>
    <clear/>
    <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
  </providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
  <providers>
    <clear/>
10     <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
11   </providers>
12 </membership>
13
4. 在PM> enable-migrations
不要忘记在model中加入我们将要添加了元素譬如这里的Mobile,Company和Position
5. 会发现我们有Configuration.cs在Migrations文件夹中 
设置AutomaticMigrationsEnabled = true;
加入,譬如:
protected override void Seed(TestProject.Models.UsersContext context)
        {
            WebSecurity.InitializeDatabaseConnection(
                "DefaultConnection",
                "UserProfile",
                "UserId",
                "UserName", autoCreateTables: true);

            if (!Roles.RoleExists("Administrator"))
10                 Roles.CreateRole("Administrator");
11
12             if (!WebSecurity.UserExists("alex"))
13                 WebSecurity.CreateUserAndAccount(
14                     "uername",
15                     "password",
16                     new { Email = "username@gmail.com", Mobile = "+176", Company = "Company_A", Position = "0" }
17                     );
18
19             if (!Roles.GetRolesForUser("alex").Contains("Administrator"))
20                 Roles.AddUsersToRoles(new[] { "alex" }, new[] { "Administrator" });
21         }
22
6. 在PM> update-database -verbose
7.  Server Explorer → Data Connections,可以找到Tables,并可以在 SQL 中运行 update query 用于加入columns
8. PM> update-database -verbose
这就是整个migrations的过程。

具体使用请参考:
http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/

2013年7月31日星期三

ASP.NET MVC 4使用技巧记录1

很早就知道ASP.NET MVC但是一直没有机会使用。编过比较多的php程序,用过Yii framework。最近决定使用ASP.NET MVC来完成一个大的实验性项目。这里简单地记录一些我在自学和编程过程中学到的技巧。
1. 新建Project很简单,选择建立ASP.NET MVC就行了。选择Project Template我比较喜欢选择Basic,这样生成的Project的东西比较少,我们可以自己进行添加修改。
2. 新建SQL数据库也很容易,在Solution Explorer中选定App_Data文件夹,右击鼠标,选择Add-->New Item..然后可以选择例如SQL Server Compact 4.0 Local Database,给一个文件名,譬如MainDb.sdf
3. 新建Table,这需要我们先走App_Data文件夹中双击MainDb.sdf,然后会出现Server Explorer窗口,选择Tables,然右击鼠标右键Create就可以添加Table了。
4. 新建ADO.NET Entity Data Model,在Solution Explorer,右击鼠标,Add-->New Item..然后可以添加ADO.NET Entity Data Model,给一个Model名字,会出现一个Choose Model Contents,我们可以选择Generate from database,点击下一步,这时就可以和我们上面建立的MainDb.sdf相连。在接下来的窗口,Choose your Database Objects and Settings选择Tables,点击完成。同意Overwrite,这就完成了。
5. 添加Controller,这很简单,在Solution Explorer中选定Conrtroller文件夹,右击鼠标,选择Add-->New Item..然后添加Controller就OK了。可以选择不同的Template,我比较喜欢使用Empty MVC controller。
6. 添加View,在ASP.NET MVC里非常方便,只需要点击譬如HomeController.cs中的public ActionResult Index(),按鼠标右键点击Add View就行了。这里有一个小技巧,我们可以选择Use a layout or master page,在下拉菜单中可以选择_Layout.cshtml。
7. 新建一个Model,在Solution Explorer中选定Models文件夹,右击鼠标,选择Add-->New Item..,点击右边的Visual C#,然后选择Class,最后给定一个名字就行了,譬如UserModel.cs,这时候我们就可以在这个Model类中添加我们需要的属性。
8. 使用第三方库的方法,在Solution Explorer中选定我们的Project,右击鼠标,选择Manage NuGet Packages,我们就可以添加譬如Json.Net库。

2013年7月25日星期四

7月闲谈

7月份最大的领悟:花钱让专业人士去做他们的工作,不要吝啬而去自己干,虽然请别人来做会多花一些钱,但是其达到的质量和效果比我们自己实现好得多,我们也节约了大量的时间成本,这些浪费掉的时间我们大可以去做更具生产力的事情,也就是我们所擅长的事情,这个道理到现在才真正的体会。这个经验一定要切记,切记!

7月份另一个的领悟:若有可能产品一定要走高端,不要去走低端,中端。试着给用户提供更多的附加价值。其实仔细算一下,做高端的产品时候会极大的提高利润率,其实成本上升的幅度更不没有想象中的高,完全可控和可以承受。

7月份还有一个领悟:我刚刚把我主导开发的软件的70%都外包出去,我发现,其实只要掌握核心,掌控流程,其他都可以外包,这样做会大量的降低工作量,并提供生产效率。而且只要监控得当,产品的质量也会得到保证。

2013的六大目标已经实现了三个。另外三个在接下来的三个月也应该会实现。刚刚定了一个新的目标,希望也能在9月底前实现,还是要努力和靠一些运气。希望得到惊喜吧。