【问题标题】:Why is my HttpPost method not firing from my Asp.Net Core Razor page?为什么我的 HttpPost 方法没有从我的 Asp.Net Core Razor 页面触发?
【发布时间】:2021-09-28 05:16:35
【问题描述】:

这里是 Asp.Net Core Razor 的新手。

我正在尝试连接一个简单的按钮来保存在我的 Razor 页面上。 我的 [HttpPost]SaveDocument() 方法未在单击“保存”按钮时触发。 相反,Index() 方法正在触发。 我不确定我连接错了什么。

这是我的 Razor 页面定义的 sn-p:

@model SampleViewModel
@{ Layout = "_DevExtremeLayout";
    ViewBag.Title = "Sampe Title";}

<form method="post">
    <div id="InputFormPanel" class="InputFormPanel">
        <partial name="@Model.ChildViewName" model="@Model.ChildViewModel" />
    </div>
    <div class="row">
        <div class="col-md-3">
            <input id="ApprovedBy" class="form-control" asp-for="ApprovedBy" />
        </div>
        <div class="col-md-2">
            <input class="form-control" asp-for="Title" />
        </div>
    </div>

    <button id="SaveButton" type="submit" >Save Form</button>               
</form>

这是我的模型:

public class SampleViewModel
{
    public object ChildViewModel { get; set; }
    public string ChildViewName { get; set; }
    public string ApprovedBy { get; set; }
    public string Title { get; set; }
}

这是我的控制器的 sn-p:

public class SampleController : Controller
{
    public async Task<IActionResult> Index(Guid documentTypeId)
    {
        SampleViewModel viewModel = new SampleViewModel()
        {
        };
        return View(viewModel);
    }

    [HttpPost]
    public async Task<IActionResult> SaveDocument(SampleViewModel sampleViewModel)
    {
        return RedirectToAction("Index");
    }
}

对此不熟悉,我想我在这里做了一些愚蠢的事情/错过了一些东西。 我在这里做错了什么?

【问题讨论】:

  • 我相信您需要将action=SaveDocument 添加到您的表单中,以便它会更改网址。就目前而言,它似乎会向没有[HttpPost] 方法的索引请求。

标签: c# asp.net-core razor


【解决方案1】:

如果您没有在 HTML 表单上分配 action 属性,它会将请求发布到您当前所在的同一页面/路由,在这种情况下是您的 Index 操作。

所以如果你像这样添加一个动作属性:

<form method="post" action="SaveDocument">

它应该开始工作了。或者,您也可以将 SaveDocument 方法重命名为 Index,因为这两个方法签名不匹配,所以不会出现任何错误。从代码组织的角度来看,这通常是我的偏好,因为它清楚地表明 GET/POST 操作是针对同一页面的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多