gpt4 book ai didi

c# - 将单个方法指定为多个 Controller URL 的目标

转载 作者:行者123 更新时间:2023-11-30 21:50:50 25 4
gpt4 key购买 nike

有很多问题都在问这个相反的逻辑,但是,我找不到我的问题的答案。我是 MVC 的新手,所以可能没有正确指定术语。

我有一个包含表单的 View ,用户可以在其中请求产品。无论产品如何,都使用相同的 View ,但特定字段显示在与该特定产品相关的表单中,例如

public class RequestController : Controller
{
// This bit works fine and displays the appropriate form in the view
public ActionResult MyProduct(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return new HttpNotFoundResult();
}
ProductRequest qd = new ProductRequest();
switch (id)
{
case "Beer":
qd.RequestType = Models.RequestType.Beer;
break;
case "Coffee":
qd.RequestType = Models.RequestType.Coffee;
break;
case "Soda":
qd.RequestType = Models.RequestType.Soda;
break;
}
return View("Index", qd);
}

// Need to get all forms rendered by the above to post here...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyProduct(ProductRequest qd)
{
if (!ModelState.IsValid)
{
return View(qd);
}
else
{
// To do ...
}
}
}

当表单在 View 中呈现时,使用...

@using (Html.BeginForm())

...呈现的 HTML 为每种产品类型显示不同的表单目标 URL,例如:

<form action="/Request/MyProduct/Beer" method="post">

无论产品类型如何,我都可以使 form action 属性使用相同的 Controller /方法吗?例如

<form action="/Request/MyProduct" method="post">

鉴于 MVC 似乎提供的灵 active ,我认为有不同的方法可以实现这一目标,但我正在寻找最佳实践作为学习经验。

最佳答案

Html.BeginForm() 调用接受各种参数,这些参数可以声明您希望表单使用的 Controller /方法。

@using (Html.BeginForm("MyProduct", "Request", FormMethod.Post, new { enctype = "multipart/form-data"}))

应该产生:

<form action="/Request/MyProduct" enctype="multipart/form-data" method="post">

关于c# - 将单个方法指定为多个 Controller URL 的目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36084286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com