razor: show editable list

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

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source