c# - 包含相同参数的 ViewResult 和 ActionResult 出错

标签 c# asp.net asp.net-mvc overloading

在我的 Controller 中,我有一个 Edit GET 方法来显示 View ,还有一个 Edit POST 方法来保存更改:

public ViewResult Edit(int id)
{
    //
}

[HttpPost]
public ActionResult Edit(int id)
{
    //
}

但我收到一条错误消息:

类型“Controllers.MyController”已经使用相同的参数类型定义了名为“Edit”的成员

我该如何解决这个问题?

最佳答案

您可以实现 View 模型,这样您的 EditViewModel 就包含您希望用户能够编辑的所有字段,并在您的 Edit GET 方法中返回这些字段,并为 View 模型提供强类型 View 。那么这意味着在您的 POST 方法中,您会将 EditViewModel 作为参数传递,有点像这样:

[HttpGet]
public ViewResult Edit(int id)
{
    //build and populate view model
    var viewModel = new EditViewModel();
    viewModel.Id = id;
    viewModel.Name = //go off to populate fields

    return View("", viewModel)
}

[HttpPost]
public ActionResult Edit(EditViewModel viewModel)
{
    //use data from viewModel and save in database
}

因此您的 GET 和 POST 方法将具有不同的签名。希望这会有所帮助。

关于c# - 包含相同参数的 ViewResult 和 ActionResult 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4698252/

相关文章:

ASP.NET 成员(member)资格在回发时强制使用 HTTPS

javascript - 添加 JavaScript 代码时如何修复 Visual Studio 中的意外标记 <

c# - 如何在 10 秒内将 200 万行插入到 sql server 中的两个表中

c# - 将数组插入xml文件

c# - 此事务是否正在为我回滚?

c# - 使用 HtmlAgilityPack 确定字符串是否仅包含允许标签列表中的标签

c# - response.redirect 后返回

c# - MSMQ,消息被放入队列并消失但从未被服务契约(Contract)接收

c# - 403.13 使用操作链接转到 {controller}/Index 时

asp.net-mvc - Azure 云服务在应用程序池回收后停止运行