Razor: Mostrar lista editável

// You need form tag in order for HttpPost. The trick is to either use for loop to generate
// correct Ids, or create Partial View.
// I like to use partial view, since it is a bit cleaner.

// For example

// ViewModel
public class SampleViewModel
{
    public IList<IncidentListmodel> IncidentListmodel = new List<IncidentListmodel>();
}


// Model
public class IncidentListmodel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Note { get; set; }
}


// View
@model AspNetMvc.Models.SampleViewModel

@foreach (var item in Model.IncidentListmodel)
{
    @Html.Partial("_UpdatePartial", item)
}


// Partial View (_UpdatePartial.cshtml)
@model AspNetMvc.Models.IncidentListmodel

@using (Html.BeginForm("Updateinc", "Home"))
{
    @Html.HiddenFor(m => m.Id)
    @Html.HiddenFor(m => m.Name)

    @Html.DisplayFor(m => m.Name)
    @Html.DisplayFor(m => m.Title)

    @Html.TextAreaFor(m => m.Note, 2, 20, new { maxlength = 50 })

    <button type="submit">Update</button>
}


// Controller
public class HomeController : Controller
{
    public ActionResult Updateinc()
    {
        var model = new SampleViewModel
        {
            IncidentListmodel = new List<IncidentListmodel>
            {
                new IncidentListmodel {Id = 1, Name = "One", Note = "Sample text"},
                new IncidentListmodel {Id = 2, Name = "Two"},
                new IncidentListmodel {Id = 3, Name = "Three"},
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Updateinc(IncidentListmodel viewModel)
    {
        // Rediret to different page.
        return RedirectToAction("Index");
    }
}
Mckynde