Home > Back-end >  ASP.NET Core MVC 3.1 form always null on POST
ASP.NET Core MVC 3.1 form always null on POST

Time:07-24

I have multiple forms in a razor view. The forms are created dynamically based on database values. Now when I post a form to server I always get empty list but validation is working. Here is my code:

View

<form id="@distinc[i].CategoryName.Replace(" ", string.Empty)" asp-action="Report" asp-controller="Laboratory">

@{
var obj = (List<ReportModel>)ViewBag.ReportModel;
var distinct = obj.DistinctBy(m => m.CategoryName).ToList();

@for (int i = 0; i < distinct.Count(); i  )
{
    <form id="@distinc[i].CategoryName.Replace(" ", string.Empty)" asp-action="Report" asp-controller="Laboratory">

        @{
            var items = obj.Where(m => m.CategoryName == distinc[i].CategoryName).ToList();
        }
        <div >
            @for (int k = 0; k < items.Count(); k  )
            {
                <input asp-for="@items[k].RequestId" hidden />
                <input asp-for="@items[k].ServiceName" hidden />
                <div >
                    <label >@items[k].ServiceName</label>
                    <input asp-for="@items[k].Result"  />
                    <span asp-validation-for="@items[k].Result" ></span>
                </div>
            }
        </div>
        <div >
            <button type="submit" >Save</button>
        </div>
    </form>
}

Actions

[HttpGet]
public async Task<IActionResult> Report(int id)
{
    var model = await laboratoryRepository.GetRequests(id);
    ViewBag.ReportModel = model;
    return View();
}

[HttpPost]
public async Task<IActionResult> Report(List<ReportModel> model)
{
        
}

Model Class

public class ReportModel : PatientInfo
{
    public long RequestId { get; set; }
    public string ServiceName { get; set; }
    public string CategoryName { get; set; }

    [Required]
    public string Result { get; set; }
}

I tried using [FromForm] attribute but no luck. What should I do?

CodePudding user response:

Make parameters name consistent. Change model to items:

[HttpPost]
public async Task<IActionResult> Report(List<ReportModel> items)
{
    ...
}

CodePudding user response:

you cannot post list of model in mvc

[HttpPost]
public async Task<IActionResult> Report(ReportModel model)
{
        
}
  • Related