【发布时间】:2021-06-05 16:53:32
【问题描述】:
我目前正在尝试构建一个具有两个提交框的“索引”表单,然后当您点击提交时,它将两个数字相加,然后显示结果。
我在没有模型的情况下尝试了这个(使用 ViewData)并设法让它工作,但我希望它与模型一起工作。我已经尝试了很多方法,但我就是看不到我错过了什么。
Journey Class - 两个字符串值和一个值(一旦我开始工作,这将是 int)
public class JourneyCalculator
{
public string PostCodeOne { get; set; }
public string PostCodeTwo { get; set; }
public string DistanceValue { get; set; }
}
然后我的控制器有两个动作,一个是标准的索引表格,一个是应该计算里程的。有了这个,我尝试了以下方法:
- 如下传递模型
- 试图从表单中传递字符串值(这只是失败)
- 只是简单地返回 View(model)
public class MapsController : Controller
{
public IActionResult Index(JourneyCalculator journeyCalculator)
{
return View(journeyCalculator);
}
[HttpPost]
public IActionResult CalculateMileage(JourneyCalculator model)
{
model.DistanceValue = model.PostCodeOne + model.PostCodeTwo;
return RedirectToAction("Index",model);
}
}
我希望将 PostCodeOne 和 PostCodeTwo 传递给“CalculateMileage”操作的表单。然后我们更新该值,然后 Model.DistanceValue 显示
<form>
<div class="form-row">
<div class="form-group col-md-6">
<label>Postcode One</label>
<input type="text" class="form-control" asp-for="PostCodeOne" placeholder="Postcode One">
</div>
<div class="form-group col-md-6">
<label>Postcode Two</label>
<input type="text" class="form-control" asp-for="PostCodeTwo" placeholder="Postcode Two">
</div>
</div>
<button type="submit" class="btn btn-primary" asp-controller="Maps" asp-action="CalculateMileage">Calculate Mileage</button>
</form>
@if(Model != null)
{
<h2>@Model.DistanceValue</h2>
}
我觉得我遗漏了一些非常明显的东西,所以任何帮助都会很棒!
当我点击“提交”时,URL 更新为 https://localhost:44301/Maps/CalculateMileage?PostCodeOne=123&PostCodeTwo=123 或 https://localhost:44301/Maps/Index?PostCodeOne=123&PostCodeTwo=123 和两者失败了,但我只想将值传递给CalculateMileage。
谢谢,
【问题讨论】:
-
当您执行 POST 请求时,您需要从请求男孩传递值,在您的示例中,您将值作为查询参数提交
-
Olegl 不是真的...只要您的控制器/动作与模型、http 方法和原始属性匹配,您就可以随意传递值
标签: c# asp.net asp.net-mvc asp.net-core