c# - 如何调用具有多个参数的 POST 方法?
问题描述
我正在构建一个 MVC 项目,将数据从我的视图发送到控制器或 apicontroller 时遇到了一些问题。我需要使用参数或对象在apicontroller中调用POST方法;
string fname = "Mark";
string lname = "Twain";
string address = "Some street";
或者
Person 类的一个实例。
- 如何发送多个参数或一个对象?
- 我应该将其直接发送到 apicontroller 还是将其发送到原始控制器?我有一个 Studentcontroller 和一个 StudentInfocontroller : apicontroller
- 我应该使用 Html.ActionLink 还是 JavaScript $.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?
}
推荐阅读
- python - 使用 ElasticSearch Python 客户端的聚合查询失败
- oracle - 计算空间数据的交集
- c++ - 为什么在 C++ VS 2019 中寻址数组范围之外的元素时不会出错
- javascript - Three.js - 如何替换 Object3D 的模型?
- python - 如何从网页内的链接中提取数据,然后将它们添加到已经存在的 csv 文件中?
- javascript - 无法在 L.Routing.control 中使用我的标记的 latLng
- php - 如何在 laravel 中更新数组
- sql-server - 在 SQL Server 的决策中避免使用聚合函数
- prometheus - prometheus 规则评估是如何工作的?
- c++ - `bool n;` `n++;` 无效但是 `n=n+1;` 或 `n=n+3` 这样的东西有效,这有什么意义?