天天看点

Asp.net MVC 学习之路-002

时间:2017-03-08

_ViewStart有局部和全局之分,如果在Views根目录下则是全局,如果在Views的子文件夹下则是局部的。

<b>int?</b>:表示可空类型,就是一种特殊的值类型,它的值可以为null,给变量(int类型)赋值为null,而不是0,防止未给id传值的时候程序报错。

public ActionResult Welcome(int? id)
        {
            ViewBag.id = id;
            return View();
        }
           

<b>重点:Html扩展方法的自定义</b>

强类型页面与弱类型页面

对于向前台传递数据

1.弱类型

后端:

public ActionResult ShowCustomer(int id)
        {
            //根据Id获取当前的Customer信息,并且展示到View
            Customer customer = new Customer() { Id = id, SName = "Fnatic", Email = "[email protected]", Age = 21 };
            //弱类型,给到前端再强转到Customer类型
            ViewData["customer"] = customer;    //将数据给到一个容器ViewDat[]
            return View();
        }
           

前端:

<div>
    @{
        var customer = ViewData["customer"] as Customer;    //从ViewData[]中取出数据再装换为Customer类型。
    }
    <table>
        <tr>
            <td>用户名:</td><td>@customer.SName</td>
        </tr>
        <tr>
            <td>年龄:</td>
            <td>@customer.Age</td>
        </tr>
        <tr>
            <td>邮箱:</td>
            <td>@customer.Email</td>
        </tr>
        <tr>
            <td>顾客编号:</td>
            <td>@customer.Id</td>
        </tr>
    </table>
</div>
           

2.强类型

public ActionResult Detail(int id)
        {
            Customer customer = new Customer() { Id = id, SName = "Fnatic", Email = "[email protected]", Age = 21 };
            ViewData.Model = customer;      //Model获取或设置与视图数据关联的模型
            return View();
        }
           
<div>
    @{
        Customer customer = ViewData.Model;
    }
    
    <table border="1px">
        <tr>
            <td>用户名:</td>
            <td>@customer.SName</td>
        </tr>
        <tr>
            <td>年龄:</td>
            <td>@customer.Age</td>
        </tr>
        <tr>
            <td>邮箱:</td>
            <td>@customer.Email</td>
        </tr>
        <tr>
            <td>顾客编号:</td>
            <td>@customer.Id</td>
        </tr>
    </table>
</div>
           

一个页面只能有一个model

所以如果有多个model应该在后端把model放进集合,再传给前端

补充: 对于HtmlHelper方法

弱类型:@Html.TextBox("asdasd");

强类型:@Html.TextBoxFor 的使用

继续阅读