Return a generic list to the MVC Controller

混江龙づ霸主 提交于 2020-01-15 10:13:10

问题


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


来源:https://stackoverflow.com/questions/5547306/return-a-generic-list-to-the-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!