行为详解:
一.常见的Controller的返回类型:ActionResult
间接或直接继承自ActionResult的类型:
几种最常见的返回结果的使用(Content,Json,Redict)
public class HelloController : Controller
{
// GET: Hello
public ActionResult Index()
{
return View();
}
public ActionResult ContentTest()
{
return Content("abc");
}
}
效果:
Json:
public ActionResult JsonTest()
{
//注意:JsonRequestBehavior.AllowGet这个不能丢否则无法正常返回 浏览器默认的请求方式为Get
return Json(new Person() {Age=11,Name="zhangsan",address="天津市"},JsonRequestBehavior.AllowGet);
}
效果:
Redirct:
public ActionResult RedictTest()
{
return Redirect(Url.Action("HtmlTest","Home"));
}
效果:
当我们访问此行为的时即可完成跳转
二.参数传递(接收):
①request[“键”]的方式进行接收 ----不常用
public ActionResult Add()
{
int id = int.Parse(Request["id"]);
ViewBag.Id = id;
return View();
}
效果:
②.自动装配
//第二种方式 自动装配
//要完成行为的重载 要满足两个条件: 1.参数不同 2.请求的方式不同
[HttpPost]
public ActionResult Add(int id) {
ViewBag.Id2 = id;
return View();
}
效果:
很明显这次走的是我们重载出来的add方法,因为我们明确规定了请求的方式。
自定义类型的自动装配
[HttpPost]
//自定义类型的自动装配
public ActionResult AddPerson(Person person)
{
ViewData.Model = person;
return View("AddPerson1");
}
@using (Html.BeginForm("AddPerson", "Hello", FormMethod.Get))
{
<span>年龄:</span>
@Html.TextBoxFor(p => p.Age);
<br />
<span>姓名:</span>
@Html.TextBoxFor(p => p.Name);
<input type="submit"/>
}
总结:
关于MVC 中行为相关的操作就介绍到这里了,这也是我学习C#中的MVC中的一点心得体会,通过这次学习我发现和java相比C#像是封装的更加”过分“,这样的好处是开发起来会更加方便但是缺点就是没有这么灵活了不能过多的进行自定义的开发,其他来说其实两种语言还是有十分多相近的地方的,比如说属性的自动装配,以及路由的配置等等。