📜  razor:显示可编辑列表 - C# 代码示例

📅  最后修改于: 2022-03-11 14:49:09.253000             🧑  作者: Mango

代码示例1
// 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 = new List();
}


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

    
}


// Controller
public class HomeController : Controller
{
    public ActionResult Updateinc()
    {
        var model = new SampleViewModel
        {
            IncidentListmodel = new List
            {
                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");
    }
}