MvcModels的用法

新建一个mvc的空项目

在Views  新建Home文件夹

在Controllers新建文件HomeController.cs文件

写入

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult RSVPForm()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ViewResult RSVPForm(GuestResponse guestResponse)
{
    return View("Thanks", guestResponse);
}

[AcceptVerbs(HttpVerbs.Post)]只相应post方式的提交,[AcceptVerbs(HttpVerbs.Get)]只相应Get的提交

在RSVPForm方法按右键选择添加视图,什么都不勾选。按Add,这样就创建了该方法的视图了。输入:

<body>
           <h1>RSVP</h1>
          <% using(Html.BeginForm()) { %>

                 <p>Your name: <%= Html.TextBox("Name") %></p>

                <p>Your email: <%= Html.TextBox("Email")%></p>

              <p>Your phone: <%= Html.TextBox("Phone")%></p>

             <p>

                      Will you attend?

                     <%= Html.DropDownList("WillAttend", new[] {

                     new SelectListItem { Text = "Yes, I'll be there",

                    Value = bool.TrueString },

                     new SelectListItem { Text = "No, I can't come",

                   Value = bool.FalseString }

                   }, "Choose an option") %>

             </p>

            <input type="submit" value="Submit RSVP" />

           <% } %>

</body>

现在主角来了

在Models里添加一个类文件名字叫GuestResponse.cs

敲入

public string Name { get; set; }

public string Email { get; set; }

public string Phone { get; set; }

public bool? WillAttend { get; set; }

好了,现在我们回头看

[AcceptVerbs(HttpVerbs.Post)]
public ViewResult RSVPForm(GuestResponse guestResponse)//这里的参数要注意一下,这里是我们在Models里定义的GuestResponse类
{
    return View("Thanks", guestResponse);
}

这个方法,我们解释一下而我们RSVPForm.aspx文件里面的表单名字每个都是跟这个GuestResponse里名字是一样的,

这样当我们提交表单的时候,mvc就会相应为我们填充里面的数据.

然后交给一个叫Thanks的视图处理。

好现在我们建立Thanks这个文件

mvc

好现在在里面输入内容

<body>

           <h1>Thank you, <%= Html.Encode(Model.Name) %>!</h1>

           <% if(Model.WillAttend == true) { %>

                      It's great that you're coming. The drinks are already in the fridge!

            <% } else { %>

                      Sorry to hear you can't make it, but thanks for letting us know.

            <% } %>

</body>

好可以测试这个程序了.

在地址栏输入http://localhost:你的端口/Home/RSVPForm

就这样了~~~有空在写~~~

原文地址:https://www.cnblogs.com/lvcha/p/1723348.html