简体   繁体   中英

.NET Core/MVC - View Posting Null Model Back to Controller

I'm using C#/.Net Core and MongoDB. My edit action takes in a model that contains a list of string values and then needs to edit each value in that list. However, when I call the edit (submit) action, my model is null or returns an empty list.

Edit get:

        [HttpGet]
        public IActionResult EditUser(string userId)
        {
           if (userId == null)
            return NotFound();

           var user = _mongoService.RecordLookup(userId);

           if (user == null)
            return NotFound();

           var viewModel = new EditRecordViewModel { Records = user };

           return View(viewModel);
        }

Edit post:

    [HttpPost]
    public IActionResult EditUser(EditRecordViewModel model)
    {
        try
        {
            foreach (var rec in model.Records)
            {
                var id = rec.Id;
                var filter = Builders<RecordModel>.Filter.Eq("Id", id);

                var modified = rec.Modified_At;
                modified = DateTime.Now;
                var updater = Builders<RecordModel>.Update.Set("Modified_At", modified);

                var val = rec.Value;
                updater = updater.Set("Value", val);

                _mongoService.EditRecord(filter, updater);
            }              
        }

        catch(Exception ex)
        {
            throw ex;
        }

        return RedirectToAction("Index");
    }

View:

    @model EditRecordViewModel


    @using (Html.BeginForm("EditUser", "Grid", FormMethod.Post))
    {
       <div class="card">           
         <div class="card-body px-lg-5 pt-0 list-group-flush form-horizontal">    
            <div class="row list-group-item form-control">
                 @foreach (var rec in Model.Records)
                    {
                        @rec.ColumnName @Html.TextBoxFor(m => rec.Value, new { @class = "form-control" })
                    }
            </div>
      </div>
      <div class="row list-group-item form-control">
          <div class="col-md-12">
              <input type="submit" class="btn btn-outline-success btn-rounded" 
               value="Save Edits" />
              @Html.ActionLink("Cancel", "Index", "Grid", null, new { @class="btn btn-outline-black btn-rounded" })
        </div>
    </div>
</div>
}

View Model:

   using System.Collections.Generic;

   namespace Medhub_API.Data.Models
   {
     public class EditRecordViewModel
     {
        public List<RecordModel> Records { get; set; }
     }
   }

I might be missing something fundamental or easy here but any suggestions are very much appreciated!

The foreach is the problem. Use a for loop and the index of the collection to get the values to be properly posted back to the controller

For example

@model EditRecordViewModel


@using (Html.BeginForm("EditUser", "Grid", FormMethod.Post)) {
   <div class="card">           
     <div class="card-body px-lg-5 pt-0 list-group-flush form-horizontal">          
        <div class="row list-group-item form-control">
            @for(var i = 0; i < Model.Records.Count; i++) {
                @Model.Records[i].ColumnName @Html.TextBoxFor(m => m.Records[i].Value, new { @class = "form-control" })
            }
        </div>
    </div>
  </div>
  <div class="row list-group-item form-control">
      <div class="col-md-12">
          <input type="submit" class="btn btn-outline-success btn-rounded" 
           value="Save Edits" />
          @Html.ActionLink("Cancel", "Index", "Grid", null, new { @class="btn btn-outline-black btn-rounded" })
      </div>
  </div>
}

Replace

@foreach (var rec in Model.Records)
{
    @rec.ColumnName @Html.TextBoxFor(m => rec.Value, new { @class = "form-control" })
}

With

@Html.EditorFor(model => model.Records)

Add a new file RecordModel.cshtml inside an EditorTemplates folder and add the following code

@model IEnumerable<RecordModel>
@foreach(var rec in Model)
{
   @rec.ColumnName @Html.TextBoxFor(m => rec.Value, new { @class = "form-control" })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM