我有一个名为Associations的视图,它有一个下拉列表和一个按钮。当用户选择一个选项并按下提交时,我希望他们转到Association / {associationKey}。协会需要处理上下岗。
目前,使用下面的代码,当表单发布时,它会转到Association并显示正确的记录,但它不会将associationKey附加到URL。
所以我得到了:
而不是:
http://localhost/Association/202
如果我手动导航到http://localhost/Association/202一切都运行正常,那么get和post都可以正常工作.... 我只想在帖子后的网址中输入密钥!
肯定有一些超级简单的事我做错了。相关代码如下。
谢谢!
协会观点:
<% Html.BeginForm("Association", "Staff", FormMethod.Post); %>
<%:Html.DropDownList("associationKey", new SelectList(Model.Associations.ToList(), "AssociationKey", "LegalName"))%>
<input type="submit" value="Edit The Selected Record" />
<% Html.EndForm(); %>
STAFF控制器:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Association(int associationKey)
{
return View("Association", new AssociationViewModel(associationKey));
}
global.asax中:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", "{action}", new { controller = "Staff", action = "Default" });
routes.MapRoute("Associations", "Associations", new { controller = "Staff", action = "Associations" });
routes.MapRoute("Association", "Association/{associationKey}", new { controller = "Staff", action = "Association" });
}
ASSOCIATION视图模型:
public class AssociationViewModel
{
public Repository db = new Repository();
public Association Association {get; private set; }
public List TelephoneTypes { get; private set; }
public AssociationViewModel(int associationKey)
{
Association = db.AssociationById(associationKey);
TelephoneTypes = db.ListTelephoneTypes().ToList();
}
}
答案 0 :(得分:2)
我认为您应该将控制器操作分离为Get操作和POST操作,如下所示:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Association(int associationKey)
{
return View("Association", new AssociationViewModel(associationKey));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Association(AssociationViewModel model)
{
return RedirectToAction("Association", new {associationKey= model.associationKey});
}
MVC框架会自动将SelectList中的选定值绑定到模型(假设模型中有一个属性来保存选定的值)。从那里你只需要重定向到传递密钥的GET方法。
答案 1 :(得分:1)
它正在做一个帖子而不是GET。这会将表单参数中的值放在url中。您可能希望使用javascript拦截表单提交,并使用location=..
<script type="text/javascript">
$(function() { // requires jQuery
$('form').submit( function() {
// maybe do some validation to ensure a legal value chosen first?
location.href = $(this).attr('action') + '/' + $(this).find('select').value();
return false; // cancel submit
});
});
</script>
<% Html.BeginForm("Association", "Staff", FormMethod.Post); %>
<%:Html.DropDownList("associationKey", new SelectList(Model.Associations.ToList(), "AssociationKey", "LegalName"))%>
<input type="submit" value="Edit The Selected Record" />
<% Html.EndForm(); %>