ASP.NET MVC-操作名称如何影响URL?
时间:2020-03-05 18:46:07 来源:igfitidea点击:
开箱即用地使用MVC,我发现生成的URL可能会产生误导,我想知道这是否可以解决,或者我的方法/理解是否错误。
假设我有一个CreateEgg页面,上面有一个表单,一旦填写并提交表单,用户就会被带到其中包含新鸡蛋的ListEggs页面。
因此,我的鸡蛋控制器将如下所示:
public class EggController : Controller { public void Add() { //do stuff RenderView("CreateEgg", viewData); } public void Create() { //do stuff RenderView("ListEggs", viewData); } }
因此,我的第一页将具有类似http:// localhost / egg / add之类的url,并且该页面上的表单将具有以下操作:
using (Html.Form<EggController>(c => c.Create())
这意味着第二页的URL为http:// localhost / Egg / Create,这对我来说是一个误导,该操作应称为Create,因为im正在创建egg,但是正在显示列表视图,因此http的URL :// localhost / Egg / List会显示更多场景。如何做到这一点而又不会使我的视图或者动作名称产生误导?
解决方案
回答
问题是行为有两件事,违反了单一责任原则。
如果创建完项目后将"创建"操作重定向到"列表"操作,则此问题将消失。
回答
Scott Gu的帖子中概述的ActionVerbs似乎是一个不错的选择。
斯科特(Scott)说:
You can create overloaded implementations of action methods, and use a new [AcceptVerbs] attribute to have ASP.NET MVC filter how they are dispatched. For example, below we can declare two Create action methods - one that will be called in GET scenarios, and one that will be called in POST scenarios
[AcceptVerbs("GET")] public object Create() {} [AcceptVerbs("POST")] public object Create(string productName, Decimal unitPrice) {}
回答
Phil Haack的方法如何成为一种行动