在一个表单(视图)中使用两个模型-ASP.NET MVC



在我在视图中创建的表单中,用户可以按add或search。如果";添加";按钮时,应该在背景中使用不同于"按钮"的模型;搜索";选项添加模型经过验证,但在其他方面与搜索模型没有区别。通过点击";搜索";不应该强迫用户填写所有字段。

代码

型号-添加型号

[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Name")]
[StringLength(200, MinimumLength = 1, ErrorMessage = "Not Allowed")]
public string Name { get; set; }
[Required]
[Display(Name = "Place")]
[RegularExpression(@"^[w ]*$", ErrorMessage = "Not Allowed")]
public string Place { get; set; }

型号-SearchModel

public int Id { get; set; }
public string Name { get; set; }
public string Place{ get; set; }

控制器

[HttpPost, ValidateAntiForgeryToken]
public IActionResult Add(AddModel p) {
if (ModelState.IsValid) {
_ = InsertData(p);
ModelState.Clear();
return RedirectToAction("Add", new { Success = true });
}
return View();
}
public IActionResult Select(SearchModel p)
{
Task.WaitAll(SelectData(p));
return View(per); // per => list of selected data
}

查看

@model **AddModel**
@if (ViewBag.success)
{
...
}
<form method="POST">
<div class="form-group">
@Html.LabelFor(m => m.Name, new { })
@Html.EditorFor(m => m.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Place, new { })
@Html.EditorFor(m => m.Place, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Place, "", new { @class = "text-danger" })
</div>
<input asp-action="Add" type="submit" class="btn btn-outline-primary" value="Add" />
<input asp-action="Select" type="submit" class="btn btn-outline-success" value="Search" />
</form>

AddModel仍在视图中使用,但我想在控制器中指定要使用的模型。所以如果你按下";搜索";SearchModel;添加";应当使用AddModel。我已经用dynamic尝试过了,但后来遇到了@html助手的问题。

有人知道吗?非常感谢;(

我认为您想要做的是称为ViewModel,这应该会有所帮助:https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3

最新更新