【问题标题】:C# .NET Core Pass HTML form variable to controllerC# .NET Core 将 HTML 表单变量传递给控制器
【发布时间】:2020-07-07 15:50:20
【问题描述】:

我在将变量从 html 表单传递到 .NET 核心项目中的控制器时遇到问题。我传递给控制器​​的变量然后在接口方法调用中使用。

我的表单数据模型:

public class JourneyFormModel
{
    public string fromStationCode { get; set; }
}

我的表格:

@model SplitTrainTicket.Models.JourneyFormModel

@using (Html.BeginForm("JounreyDetails", "Home", FormMethod.Post))
{
<div class="form-horizontal col-md-6">

    <div class="autocomplete">
        @Html.EditorFor(model => model.fromStationCode, new { htmlAttributes = new { @class = "autocomplete", id = "departStationPicker", @placeholder = "Departing From" } })
    </div>
}

还有我的控制器:

 [HttpPost]

 public IActionResult GetResults(JourneyFormModel form)
    {
        return Ok(_repository.GetAllResults(form.fromStationCode));
    }

    

当 form.toStationCode 传递给我的 GetAllResultsMethod 时,该值似乎为 null。我已经用字符串手动厌倦了这个,它似乎工作正常。从表单字段中获取字符串似乎是一个问题。

如果有帮助的话,这也是我的界面:

public interface IJourneyDetailsRepository
{
    List<JourneyModel> GetAllResults(string fromStation);
}

提前感谢任何阅读本文的人:)

【问题讨论】:

  • 几个问题:1) 似乎fromStationCode 是表中的主键和身份,您将其放在那里让用户更改它? 2)您的表单发回主控制器 jounreyDetails 方法,但您的控制器示例显示了不同的。 3)您的控制器示例没有 [HttpPost] 注释,因此它是一个 GET 方法。您的表单和控制器不相互通信。
  • 我的错,我做了修改
  • 将控制器注释更改为 HttpPost 时仍然没有运气
  • 请阅读我的问题 #2。您的表单正在发回 /home/jounreyDetails 但您的控制器(我不知道控制器的名称)只有 GetResults 方法。您的表单没有与您的控制器对话。
  • 我明白了。我会花一些时间在这上面。感谢您为我指明正确的方向

标签: c# html asp.net-core razor asp.net-core-mvc


【解决方案1】:

从表单域获取字符串似乎是个问题。

Html.BeginForm 中的动作名称为JounreyDetails,而您要将表单发布到GetResults 动作,则需要更改它。

@using (Html.BeginForm("GetResults", "Home", FormMethod.Post))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多