首页 > 解决方案 > 如何调用具有多个参数的 POST 方法?

问题描述

我正在构建一个 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?

标签: c#asp.net-mvcparametershttp-post

解决方案


您可以使用帖子或许多其他方式来获取数据,但如果它是一个表单并且您使用的是 asp.net,Razor 会为您处理。 Html.BeginForm假设您有一个模型,该模型将由用户通过 texboxes 或其他控件进行更新。然后单击一些按钮将进行呼叫。通知<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?
}

推荐阅读