简体   繁体   中英

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

In my form, which I created in a view, the user can press add or search. If the "add" button is pressed, a different model should be used in the background than with the "search" option. The add model is validated but otherwise does not differ from the search model. By clicking "search" the user shouldn't be forced to fill in all fields.

Code

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
}

View

@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>

The AddModel is still used in the View, but I would like to specify in the controller which model I would like to use. So if you press "search" the SearchModel and with "add" the AddModel should be used. I've already tried it with dynamic, but then it came to problems with the @html helpers.

Does somebody has any idea? Would appreciate;)

I think what you are looking to do is called a ViewModel, this should help: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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