Return a generic list to the MVC Controller

2019-08-12 22:44发布

问题:

I have a class that looks like this;

public class item
{
    public string Tradingname { get; set; }
}

I have a Partial View that inherits from the "item" class;

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<item>" %>

<%= Html.TextBoxFor(x => x.Tradingname) %>

In my view I create a number of them. Let's Say 2;

<% using (Html.BeginForm())
   { %>
<% Html.RenderPartial("TradingName", new Binding.Models.item()); %><br />
<% Html.RenderPartial("TradingName", new Binding.Models.item()); %><br />

<input type="submit" />

<%} %>

Then in my controller I was hoping to be able to write this;

    [HttpPost]
    public ActionResult Index(List<item> items)

or

    [HttpPost]
    public ActionResult Index([Bind(Prefix = "Tradingname")]List<item> items)

But I can't seem to get any data back from my partial views into my List. Anyone know how I can get a variable list of data back from a variable set of partialViews?

回答1:

I would recommend you using editor templates:

Controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        List<item> model = ...
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(List<item> items)
    {
        ...
    }
}

and in the view:

<% using (Html.BeginForm()) { %>
    <%= Html.EditorForModel();
    <input type="submit" />
<% } %>

and finally simply move the partial in ~/Views/Home/EditorTemplates/item.ascx (name and location are important):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<item>" %>
<%= Html.TextBoxFor(x => x.Tradingname) %><br/>