【发布时间】:2016-10-18 00:48:44
【问题描述】:
我需要一些关于如何完成这项工作的帮助/建议。 我需要通过 ActionLink 将模型从视图传递到控制器
@Html.ActionLink("Radera", "DeleteTraffic", new { model = Model, trafficId = traffic.Id }, new { @class = "btn btn-link NoBorder NoBackGround" })
控制器中的方法如下所示。
public ActionResult DeleteTraffic(CalendarModel model, int trafficId)
{
return View("EditDay", model);
}
我还没有在方法中添加任何代码,我只是在调试它以使调用工作。当我按下按钮时模型为空,然而,trafficId 已正确设置。那我做错了什么?
编辑 1: 我已经根据这里的建议更改了代码。
@using (Html.BeginForm("DeleteTraffic", "Calendar", new {trafficId = traffic.Id})) {<input type="submit" value="Radera" class="btn btn-link NoBorder NoBackGround"/>}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("DeleteTraffic")]
public ActionResult DeleteTraffic(int trafficId)
{
return View("EditDay", Model);
}
但 DeleteTraffic 永远不会重新处理,而是调用此页面的主要操作。
// GET: Calendar
public ActionResult Calendar()
{
CalendarModel model = new CalendarModel {SelectedDate = DateTime.Today};
if (Request.HttpMethod == "POST")
{
if (!string.IsNullOrEmpty(Request.Form.Get("submit.SelectDate")))
{
model.SelectedDate = Convert.ToDateTime(Request.Form["selectedDate"]);
model.TrafficDates = TrafficData.GeTrafficDatesPerMonth(model.SelectedDate);
Model = model;
return View("EditDay", Model);
}
}
Model = model;
return View(Model);
}
我是否应该将 trafficId 塞入一个隐藏字段并将此操作用于所有操作? MVC 有时看起来很不灵活......
【问题讨论】:
-
它
new { Model, trafficId = traffic.Id }但如果模型的任何属性是复杂对象或集合,它将无法正确绑定(并且您可能超过查询字符串限制。为什么您认为您需要这样做 - 您应该只是传递模型的ID属性,而不是整个模型。删除永远不应该是 GET。您应该使用表单并发布 ID 值 -
我可以只发送 trafficId 并忽略模型。我这样做的原因是在处理完删除后返回编辑站点。加载站点时,模型对象是必不可少的,这就是我来回传递它的原因。我可以将它存储在会话变量中,但我不知道是否有更好的方法。我不想做表单和发布的原因是 CalendarModel 包含大量数据,我不希望应用程序在用户每次按下按钮时都继续重建
-
更好的方法是再次从数据库中获取它。如果它确实包含大量数据,那么由于查询字符串的限制,您几乎肯定会抛出异常。但正如我所指出的,Delete 必须是 POST,而不是 GET。
-
那么我如何将 ActionLink 变成帖子?我需要在控制器中的方法上添加一个属性吗?
-
@using(Html.BeginForm("DeleteTraffic", "yourControllerName", new { trafficId = traffic.Id })) { <input type="submit" value="Radera" /> }并用[HttpPost]标记方法(您可能还需要AntiForgeryToken)
标签: asp.net-mvc-5