简体   繁体   中英

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.

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.

However, when clicking on the submit button the 'tenant' string returns null in the controller...

What am I missing?

Thanks!

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

    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.

In Asp.net core MVC, you can use tag helper asp- to implement it.

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

You need to wrap your dropdown in form tag and post form to the action.

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