Return a collection of models from a view

2019-08-27 09:47发布

问题:

I have a requirement to dynamically create objects in my Razor View and after the user edits them, submit them back to the server.
This is how my model looks like:

public class Panel
{
    public string Name { get; set; }
    public string Text1 { get; set; }
    public string Text2 { get; set; }
}

What I want to do is to render the required inputs each time the clicks on a button using Javascript. this is how my main view looks like:

@model IEnumerable<TabsTest.Models.Panel>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    @for (int i = 0; i < ViewBag.I; i++)
    {

        @*@Html.Partial("_view", new TabsTest.Models.Panel() { Name = "A" + i })*@
        @Html.Action("PanelSub", "Panels", new { name = i })
        <hr />
    }
    <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
</div>
}

The PartialView:

@model TabsTest.Models.Panel
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Text1, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Text2, new { htmlAttributes = new { @class = "form-control" } })

And my Actions:

    public ActionResult CreatePanels()
    {
        ViewBag.I = 5;
        return View();
    }

    [HttpPost]
    public ActionResult CreatePanels(IEnumerable<Panel> panels) // <= always returns Null
    {
        //handle collection...
        return RedirectToAction("Index");
    }

    public PartialViewResult PanelSub(int name = -1)
    {
        var panel = new Panel() { Name = name.ToString() };
        return PartialView("_view");
    }

My question is how can I use the model binding to handle the new objects that the user created in the view?

回答1:

You can create a dummy set of inputs that are cloned and displayed when you click an 'add panel' button (assumes you are adding new panels to a div with id='#Panels')

<div id="NewPanel" style="display:none">
  <div class='panelContainer'>
    <input type="text" name="panel[#].Name" value />
    <input type="text" name="panel[#].Text1" value />
    <input type="text" name="panel[#].Text2" value />
    <input type="hidden" name="panel[#].Index" value ="%"/>
  </div>
</div>

Note the use of a dummy indexer to prevent this one being posted back

And the script

$('#AddButton').click(function() {
  var index = $('#Panels').children('.panelContainer').length; // count of existing panels
  var clone = $('#NewPanel').clone();
  // Update the index of the clone
  clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
  clone.html($(clone).html().replace(/"%"/g, '"' + index  + '"'));
  $('#Panels').append(clone);
}

Note you do not need the partial view with this solution



回答2:

This is how I went about it: I used knockoutjs and AJAX. I had a collection whatever from the server. I retrieved the collection via AJAX and populated the knockout viewmodel. On the view, I implemented adding new items. When I added a new item:

  1. the item was added in the ko viewmodel
  2. the item was sent via ajax to the server to be saved