dev*_*ium 0 .net c# asp.net asp.net-mvc asp.net-mvc-3
所以,我正在试验ASP.NET MVC,我有以下代码:
public class TrollController : Controller
{
public ActionResult Index()
{
var trollModel = new TrollModel()
{
Name = "Default Troll",
Age = "666"
};
return View(trollModel);
}
[HttpPost]
public ActionResult Index(TrollModel trollModel)
{
return View(trollModel);
}
public ActionResult CreateNew()
{
return View();
}
[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
return RedirectToAction("Index");
}
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是建立一个索引页面,显示我们的巨魔的年龄以及他的名字.
有一个动作可以让我们创建一个巨魔,在创建它之后我们应该回到索引页面,但这次是我们的数据,而不是默认数据.
有没有办法通过TrollModel CreateNew(TrollModel trollModel)接收Index(TrollModel trollModel)?如果有,怎么样?
最好的方法是将troll持久保存在服务器上(数据库?),然后在重定向时只将id传递给索引操作,以便可以将其取回.另一种可能性是使用TempData或Session:
[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
TempData["troll"] = trollModel;
return RedirectToAction("Index");
}
public ActionResult Index()
{
var trollModel = TempData["troll"] as TrollModel;
if (trollModel == null)
{
trollModel = new TrollModel
{
Name = "Default Troll",
Age = "666"
};
}
return View(trollModel);
}
Run Code Online (Sandbox Code Playgroud)
TempData只能在单个重定向中生存,并在后续请求中自动逐出,而Session将在会话的所有HTTP请求中保持不变.
另一种可能性包括在重定向时将troll对象的所有属性作为查询字符串参数传递:
[HttpPost]
public ActionResult CreateNew(TrollModel trollModel)
{
return RedirectToAction("Index", new
{
Age = trollModel.Age,
Name = trollModel.Name
});
}
public ActionResult Index(TrollModel trollModel)
{
if (trollModel == null)
{
trollModel = new TrollModel
{
Name = "Default Troll",
Age = "666"
};
}
return View(trollModel);
}
Run Code Online (Sandbox Code Playgroud)
现在您可能需要重命名Index POST操作,因为您不能有两个具有相同名称和参数的方法:
[HttpPost]
[ActionName("Index")]
public ActionResult HandleATroll(TrollModel trollModel)
{
return View(trollModel);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1924 次 |
| 最近记录: |