【发布时间】:2019-10-07 15:55:16
【问题描述】:
我有一个任务,我需要在一个表单中捕获三个值,提交它们,根据某些条件对这些值执行特定操作,这将引导我找到数据库行的索引,从数据库中获取一行使用计算出的索引,然后更新视图。
问题在于表单本身不是模型,也不会在表中创建实例/实体/行。当我创建视图时,我从 Razor 收到一个错误,说表达式树可能不包含动态操作,我知道这是因为表单与任何模型都不相关(因此我没有在.cshtml 文件)。我想我需要将内容发布到控制器并使用获取的值更新内容(我确实尝试使用提交按钮,但它会将我重定向到一个空页面,我知道这就是表单通常的功能,但这不是行为我需要)。
我尝试将 @model 指令添加到包含表单的 Index.cshtml 文件中,但由于我附加索引的模型不包含与我在表单中使用的相同的属性,因此 Razor 会抛出错误。我尝试为表单创建一个模型类,它以某种方式工作,我得到了所有值(它在提交时重定向,这不是我想要的)但我不相信这是正确的做法,因为表单本身不是用于在表中创建实体。
这是我将从数据库中获取值的模型:
using System;
using System.Collections.Generic;
namespace PrototipoExploratorio.Models
{
public partial class Factores
{
public int FactorId { get; }
public int ValorUno { get; }
public int ValorDos { get; }
public int ValorTres { get; }
}
}
这是表格,目前在文件夹 Views/Factores 中(如上图所示)
@{
ViewData["Title"] = "Index";
}
<h2>Factores</h2>
<form method="post" asp-controller="FactoresForm" asp-action="ObtenerFactor">
<div class="form-group">
<label for="Estatura" class="control-label">Estatura en centímetros</label>
<input asp-for="Estatura" name="estatura" type="number" id="estatura" placeholder="168, 190, 155...">
</div>
<div class="form-group">
<label for="Edad" class="control-label">Edad</label>
<input asp-for="Edad" name="edad" type="text" id="number" placeholder="15, 24, 50...">
</div>
<div class="form-group">
<label for="Peso" class="control-label">Peso en kilogramos</label>
<input asp-for="Peso" name="peso" type="number" id="peso" placeholder="80, 70.5, 55.40...">
</div>
<div class="form-group">
<label for="EstadoCivil" class="control-label">Estado civil</label>
<select id="EstadoCivil" asp-for="EstadoCivil" for="EstadoCivil" name="EstadoCivil">
<option value="soltero">Soltero</option>
<option value="casado">Casado</option>
</select>
</div>
<div class="form-group">
<div>
<label class="control-label">Factor calculado: </label>
<h6 id="FactorCalculado">{this is where I will update the value calculated from the values submitted here and the database row that I will fetch}</h6>
</div>
<div class="form-group">
<button asp-controller="FactoresForm" asp-action="ObtenerFactor" class="btn btn-primary" type="submit">Obtener factor</button>
<button asp-controller="FactoresForm" asp-action="LimpiarDatos" class="btn btn-primary" type="submit">Limpiar</button>
</div>
</div>
</form>
这是控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PrototipoExploratorio.Models;
namespace PrototipoExploratorio.Controllers {
public class FactoresForm : Controller {
// GET: /<controller>/
public IActionResult Index() {
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
// I expect to reach this code on form submit
// I know that right now this does not work given the explanation above
public IActionResult ObtenerFactor() {
Console.WriteLine("");
return View("Index");
}
}
}
我希望提交表单,做一些业务逻辑操作来获取数据库行的索引(映射到 Factores 模型),从行中获取值并更新视图。
【问题讨论】:
标签: c# asp.net-mvc asp.net-core razor