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:

1  @{
2  Layout = null;
3  }
4  <!DOCTYPE html>
5  <html>
6  <head>
7  <meta name="viewport" content="width=device-width" />
8  <title>Index</title>
9  </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:

1  using System;
2  using System.Collections.Generic;
3  using System.Linq;
4  using System.Web;
5  using System.Web.Mvc;
6  using PartyInvites.Models;
7  namespace PartyInvites.Controllers {
8  public class HomeController : Controller {
9      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

1  @model PartyInvites.Models.GuestResponse
2  @{
3  Layout = null;
4  }
5  <!DOCTYPE html>
6  <html>
7  <head>
8  <meta name="viewport" content="width=device-width" />
9  <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

1  @model PartyInvites.Models.GuestResponse
2  @{
3  Layout = null;
4  }
5  <!DOCTYPE html>
6  <html>
7  <head>
8  <meta name="viewport" content="width=device-width" />
9  <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()

譬如:

1  @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
2 
3     @Html.AntiForgeryToken()
4 
5     @Html.ValidationSummary(true)
6 
7     <fieldset>
8 
9         <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” 部分中加入:
1  <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
2    <providers>
3      <clear/>
4      <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
5    </providers>
6  </roleManager>
7  <membership defaultProvider="SimpleMembershipProvider">
8    <providers>
9      <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;
加入,譬如:
1  protected override void Seed(TestProject.Models.UsersContext context)
2          {
3              WebSecurity.InitializeDatabaseConnection(
4                  "DefaultConnection",
5                  "UserProfile",
6                  "UserId",
7                  "UserName", autoCreateTables: true);
8 
9              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月底前实现,还是要努力和靠一些运气。希望得到惊喜吧。

2013年6月30日星期日

JavaCV Installation and Using it in Eclipse

I always use C++ with OpenCV libs for coding the computer vision program, but I just find a nice library called JavaCV (wrapper classes used for openCV). It allows anyone to use OpenCV functions directly in desktop Java. Now I can write computer vision program with Java, great!

The links below is a basic guide to help anyone port their OpenCV code to JavaCV.
http://code.google.com/p/javacv/wiki/ConvertingOpenCV

Here I give a very short intro about how to set up JavaCV and use it.
A.
Download OpenCV-2.4.5.exe and javacv-0.5-bin.zip, from:
http://sourceforge.net/projects/opencvlibrary/files/
http://code.google.com/p/javacv/

B.
Install OpenCV-2.4.5
Extract javacv-0.5-bin.zip

C.
set the environment variables:
the user variables for you, such as:
CLASSPATH → D:\project\opencv\build\x86\vc10\lib;
PATH → D:\project\opencv\build\java\x86;D:\project\opencv\build\x86\vc10\bin

D.
Start Eclipse
create new java project →
click next →
1. add project to the build path
2. in Libraries tab → Add External JARs... → add javacv-bin\javacpp.jar, javacv-bin\javacpp.jar, javacv-bin\javacv-windows-x86.jar
3. in Order and Export tab → click all of these libraries we added
→ click finish
in the project → add a new class


E.
Copy the test code below, to run the test program, copy a img.jpg in the project folder:

1  import static com.googlecode.javacv.cpp.opencv_core.*;
2  import static com.googlecode.javacv.cpp.opencv_imgproc.*;
3  import static com.googlecode.javacv.cpp.opencv_highgui.*;
4 
5 
6  public class test {
7      /**
8       * @param args
9       */
10     public static void main(String[] args) {
11         IplImage img = cvLoadImage("tmp.jpg");
12         
13         cvShowImage("test image", img);
14         cvWaitKey();
15         cvReleaseImage(img);
16     }
17 }
18

F.
in the menu → Project → Build All → Run the project

2013年6月24日星期一

Using WordPress for our company’s website


I just switch to use the WordPress for our company’s website. WordPress is very easy to use and has an intuitive interface. I found that the time spent on formatting is greatly reduced.I choose 3 plugins and a beautiful theme for our site. Below is a short intro about them.
Plugins:
  • qTranslate
  • Contact Form 7
  • WP-Mail-SMTP
A: Setting of WP-Mail-SMTP
1. in WP-Mail-SMTP:
need to set:
  • From Email
  • From Name
set Mailer “Send all Wordpress email via SMTP”
2. in STMP Options
need to set:
  • SMTP Host
  • SMTP Port
  • Encryption → No encryption
  • Authentication → Yes: use SMTP authentication
  • Username: your mail username
  • Password: your mail password
B: Setting of Contact Form 7
Set your email-SMTP in the form field.

Copy this code and paste it into your post, page or text widget content.
For Example: [contact-form-7 id="48" title="Contact form 1"]

C: qTranslate
ignore message “qTranslate Services could not load OpenSSL!”
You can add Language in the setting page.
→ In the Widget Page of the WordPress add the qTranslate Language Chooser to the Header

Theme:
I choose Pinboard, cause it is a crafty and elegant theme powered by an advanced theme framework and grid system. It looks beautiful. It is also a Free Responsive WordPress Theme for the business or personal site. It is very easy to customize the site title & tagline, colors, header or background image, navigation and static front page. It also integriert the SEO tool.

2013年6月6日星期四

VS 2008编译strmbase.lib

最近写程序很少,因为有两个手下帮我写,一个星期编不超过8小时程序吧,但是写的东西很杂,Java,C++,Matlab等等。今天需要使用一个同事很早以前写的AVI2Grabber模块对Lagarith Lossless Avi Video读取,里面使用了strmbase.lib有关于DirectShow的东西。

研究了一下才发现strmbase.lib并不在MS配的SDK \lib. 需要自己编译一个。

  • 下载并安装Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1
  • 安装后,可以在C:\Program Files\Microsoft SDKs\Windows\v7.0\Samples\multimedia\directshow\baseclasses找到baseclasses.sln,然后用VS 2008打开。
  • 用VS2008在Release下进行编译(编译模式“Debug” 改成 “Release”),可以在C:\Program Files\Microsoft SDKs\Windows\v7.0\Samples\multimedia\directshow\baseclasses\Release得到我们需要的strmbase.lib。