繁体   English   中英

在一种形式中使用两个模型(视图) - ASP.NET MVC

[英]Use two models in one form (view) - ASP.NET MVC

在我在视图中创建的表单中,用户可以按添加或搜索。 如果按下“添加”按钮,则应在后台使用与“搜索”选项不同的 model。 添加 model 已验证,但在其他方面与搜索 model 没有区别。 通过单击“搜索”,用户不应被迫填写所有字段。

代码

Model - AddModel

[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; }

Model - SearchModel

public int Id { get; set; }

public string Name { get; set; }

public string Place{ get; set; }

Controller

[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 仍在视图中使用,但我想在 controller 中指定我想使用哪个 model。 因此,如果您按“搜索” SearchModel 并使用“添加”,则应使用 AddModel。 我已经尝试过动态的,但后来遇到了@html 助手的问题。

有人有什么想法吗? 将不胜感激;)

我认为您要执行的操作称为 ViewModel,这应该会有所帮助: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music -store-part-3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM