【问题标题】:How to call a POST method with multiple parameters?如何调用具有多个参数的 POST 方法?
【发布时间】:2020-12-02 18:45:48
【问题描述】:

我正在构建一个 MVC 项目,但在将数据从我的视图发送到控制器或 apicontroller 时遇到了一些问题。 我需要在apicontroller中使用参数或对象调用POST方法;

string fname = "Mark"; 
string lname  = "Twain";
string address = "Some street";

Person 类的一个实例。

  1. 如何发送多个参数或一个对象?
  2. 我应该将它直接发送到 apicontroller 还是发送到原始控制器?我有一个 Studentcontroller 和一个 StudentInfocontroller : apicontroller
  3. 我应该使用 Html.ActionLink 还是 JavaScript $.post?

【问题讨论】:

  • 用户是否填写了您需要发送的信息?
  • 是的,信息来自用户输入
  • 那么我的回答如下。我认为Html.BeginForm 是您要找的。​​span>
  • 我复制了一个 contraller 调用并将其粘贴到我的 studentinfocontroller : apicontroller 并且我在其他部分遇到了一些错误。只是为了确定,将它放在 Studentcontroller 或 Studentcontroller 中是最好的方法:apicontroller?
  • 这真的很主观,取决于每个控制器的职责。它适用于这两种情况,但我认为将所有以学生为中心的行动集中在一个地方会很好。您可以根据需要在控制器中执行任意数量的操作。只需要在提交时返回一个确认页面。

标签: c# asp.net-mvc parameters http-post


【解决方案1】:

您可以使用帖子或许多其他方式来获取数据,但如果它是一个表单并且您使用的是 asp.net,Razor 会为您处理。 Html.BeginForm 假设您有一个模型,该模型将由用户通过 texbox 或其他控件进行更新。然后单击一些按钮将进行呼叫。注意<button type="submit"> 告诉表单,当按下按钮时,将调用服务并发布模型对象。

这个答案是使用Html.BeginForm 的基础。您需要更深入地挖掘才能获得良好的理解。

@model Student
@using (Html.BeginForm("InsertStudent", "StudentInfocontroller"))
{
   // style it appropriately
   @Html.TextBoxFor(m => m.fName)
   @Html.TextBoxFor(m => m.lName)
   <button type="submit" class="btn">Submit</button>
}

控制器调用。

[Route("InsertStudent")]
public async Task<IActionResult> InsertStudent(Student student)
{
   // do something with the student object received. Like insert or update the database.

   Repository.InsertOrUpdate(student); // assuming you have a repository.

   return View("Confirmation", student); <--- let the user know?
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    相关资源
    最近更新 更多