[英]ASP.NET Core MVC - Passing Model Data Back to Controller from View
Should be a relatively simple question but currently I'm not able to pass model values updated in the view back to the controller.应该是一个相对简单的问题,但目前我无法将视图中更新的 model 值传递回 controller。
As you can see below we have a very simple dropdown list in the view.正如您在下面看到的,我们在视图中有一个非常简单的下拉列表。 The 'tenant' string in the Model should be getting set with whichever value is selected in the dropdown list. Model 中的“租户”字符串应该设置为在下拉列表中选择的任何值。
However, when clicking on the submit button the 'tenant' string returns null in the controller...但是,当单击提交按钮时,“租户”字符串在 controller 中返回 null...
What am I missing?我错过了什么?
Thanks!谢谢!
Model: Model:
public class TenantModel
{
public List<string> tenantList { get; set; }
public string tenant { get; set; }
}
View:看法:
@model TenantModel
@{
ViewData["Title"] = "Manage";
}
<h1>Manage Databases</h1>
@Html.DropDownListFor(m => m.tenant, new SelectList(Model.tenantList), "Select Tenant", new { @class = "dropdown", @style = "width: 220px" })
<br />
<button type="submit" onclick="location.href='@Url.Action("DropDbs", "Environments", Model)'" class="btn btn-danger">Destroy</button>
Controller Controller
public class EnvironmentsController : Controller
{
public IActionResult Manage()
{
var tenantModel = new TenantModel();
tenantModel.tenantList = Utils.TenantList();
return View(tenantModel);
}
public IActionResult DropDbs(TenantModel tenantModel)
{
return RedirectToAction("Manage");
}
}
I want to have multiple buttons on the form each targeting a different action inside my controller.我想在表单上有多个按钮,每个按钮针对我的 controller 中的不同操作。
In Asp.net core MVC, you can use tag helper asp-
to implement it.在Asp.net核心MVC中,可以使用tag helper asp-
来实现。
<form method="post">
@Html.DropDownListFor(m => m.tenant, new SelectList(Model.tenantList), "Select Tenant", new { @class = "dropdown", @style = "width: 220px" })
<br />
<button type="submit" asp-action="Action1" asp-controller="Controller" class="btn btn-danger">Operate1</button>
<button type="submit" asp-action="Action2" asp-controller="Controller" class="btn btn-danger">Operate2</button>
<button type="submit" asp-action="Action3" asp-controller="Controller" class="btn btn-danger">Operate3</button>
</form>
You're all doing wrong.你们都做错了。 You're redirecting to action and passing a Model but problem is that not going to fill by your dropdown that why it's null.您正在重定向到操作并传递 Model,但问题是您的下拉列表不会填写为什么它是 null。
You need to wrap your dropdown in form tag and post form to the action.您需要将下拉列表包装在表单标签中并将表单发布到操作中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.