asp.net mvc 参数传递的问题

来源:互联网 发布:以太网端口 编辑:程序博客网 时间:2024/05/22 08:05

要实现的交互使用带参数的Action与没带参数的Action的问题使用

在Views中:

@using MedCrab.Core.Model.APP@model User<form  method="post">   用户名:@Html.TextBoxFor(m=>m.UserName)   密码:  @Html.TextBoxFor(m=>m.Password)   昵称:  @Html.TextBoxFor(m=>m.fNickName)   性别:           @Html.RadioButtonFor(m => m.fSex,true)男          @Html.RadioButtonFor(m => m.fSex,false)女   学校: <select name="fschool">             <option value="四川理工">四川理工学院</option>             <option value="长江师范">长江师范学院</option>             <option value="成都工程">成都工程学院</option>             <option value="西南交通">西南交通大学</option>          </select>   <button type="submit">确定</button></form>

使用@model强类型,在select中的fschool中,model user有fschool,所以后台会取得到这个值,而如果是后台向前台进行数据绑定的话,这里的select没有进行动态数据绑定,自然不会出现数据库中fschool的数据值。

而其中@Html.TextBoxFor与@Html.RadioButton则是后台代码,后台向前台进行数据绑定的话,自然是可以成功进行显示的。

其中 => 标记称作 lambda 运算符。 该标记在 lambda 表达式中用来将左侧的输入变量与右侧的 lambda 体分离。 Lambda 表达式是与匿名方法类似的内联表达式,但更加灵活;在以方法语法表示的 LINQ 查询中广泛使用了 Lambda 表达式。

在Controller中:

    [HttpGet]        //对应Test页面,服务器向客户端发送一个页面        //URl带参数:http://localhost:8001/my/#/Test/Test?userId=7dd555b1-95ac-4872-9a3c-28954da26cfe 进行检测        public ActionResult Test(string userId)        {            if (string.IsNullOrEmpty(userId))             //为空,直接返回视图            {                return View();            }            //不为空,将已有信息呈现在视图中            else             {               userService = new UserService();              User user = (User)userService.GetModelByID(userId);              return View(user);            }                                }         /// <summary>         /// 修改个人资料         /// </summary>         /// <returns></returns>         [HttpPost]        //对应Test页面,客户端向服务器请求一个页面        public ActionResult Test(User userModel)        {             userService = new UserService();             //用户名是否为空             if(string.IsNullOrEmpty(userModel.UserName))                return this.ErrorJson(null,"没有填写用户名!");            //判断数据库中是否存在此用户             if (!userService.IsExist(string.Format("Phone='{0}'", userModel.UserName)))             {    //不存在此用户,进行新增用户操作                 if (userService.EditUser(userModel))                 {                     return this.SuccessJson(null, "新增用户资料成功");                 }                 else return this.ErrorJson(null, "新增用户资料失败");             }             else {                  //取得ID                 userModel.ID = userService.GetByUserName(userModel.UserName).ID;                //更新资料,返回视图                if (userService.EditUser(userModel))                         return this.SuccessJson(null, "修改用户资料成功");                else  return this.ErrorJson(null, "修改用户资料失败");             }        }
注意在Action中参数问题。如果是string字符串,即使是空的,也不会报错,即会为空。如是int类型的,若参数为空,则会报错404或者参数未引用到实例等错误。

同一个View可以对应同名的Action方法,其中可以定义不同类型,个数的参数传递,也可以限定httppost与httpget特性。

其中get请求带参数则在浏览器中会显示,post则不会。

简单交互图:





0 0