Hello everyone, am trying to pass a list of data in a form from a view to mvc controller. there is no model for it

Abdullahi Ohiare 0 Reputation points
2024-11-11T15:27:35.3266667+00:00

this is the view code

@{
ViewData["Title"] = "Result Table";
}
<dv>
<form action="/Home/CalculateGpa" method="post">
    <table>
        <tr>
            <td><input type="text" name="subject" placeholder="Maths" readonly /></td>
            <td><input type="number" name="creditUnits" placeholder="Credit unit" /></td>
            <td><select name="gradePoint">
                    <option value="5"> A</option>
                    <option value="4"> B</option>
                    <option value="3"> C</option>
                    <option value="2"> D</option>
            </select></td>
        </tr>
        <tr>
            <td><input type="text" name="subject" placeholder="English" readonly /></td>
            <td><input type="number" name="creditUnits" placeholder="Credit unit" /></td>
            <td>
                <select name="gradePoint">
                    <option value="5"> A</option>
                    <option value="4"> B</option>
                    <option value="3"> C</option>
                    <option value="2"> D</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="text" name="subject" placeholder="Chemistry" readonly /></td>
            <td><input type="number" name="creditUnits" placeholder="Credit unit" /></td>
            <td>
                <select name="gradePoint">
                    <option value="5"> A</option>
                    <option value="4"> B</option>
                    <option value="3"> C</option>
                    <option value="2"> D</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input type="text" name="subject" placeholder="Physics" readonly /></td>
            <td><input type="number" name="creditUnits" placeholder="Credit unit" /></td>
            <td>
                <select name="gradePoint">
                    <option value="5"> A</option>
                    <option value="4"> B</option>
                    <option value="3"> C</option>
                    <option value="2"> D</option>
                </select>
            </td>
        </tr>
    </table>
    <button type="submit" name="GpaCalculator">Calculate GPA</button>
</form>

this is the controller code.

using GPA_CALCULATOR.Models; 
using Microsoft.AspNetCore.Mvc; using System.Diagnostics;
namespace GPA_CALCULATOR.Controllers 
{ 
    public class HomeController : Controller 
   { 
    private readonly ILogger<HomeController> _logger;
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
    public IActionResult Index()
    {
        return View();
    }
    public IActionResult Privacy()
    {
        return View();
    }
    [HttpPost]
    public IActionResult CalculateGpa()
    {
        var subjects = Request.Form["subjects"];
        var creditUnits =Request.Form["creditunits"];
        var gradePoint = Request.Form["gradepoints"];
       
        int totalCredits = 0;
        int totalGradePoints = 0;
        for (int i = 0; i < subjects.Count; i++)
        {
            
            int credit = int.Parse(creditUnits[i]);
            int grade = int.Parse(gradePoint[i]);
            
            totalCredits += credit;
            totalGradePoints += grade * credit;
        }
        int GpaCalculator = (int)totalGradePoints + totalCredits;
        
        ViewBag.GPA = GpaCalculator;
        return View("Privacy");
    }
    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
  }
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,684 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,123 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,306 Reputation points
    2024-11-11T17:05:58.93+00:00

    the subjects name in the form is "subject" and the gradepoint name is "gradepoint". try:

            var subjects = Request.Form["subject"];
            var creditUnits =Request.Form["creditunits"];
            var gradePoint = Request.Form["gradepoint"];
    
    0 comments No comments

  2. SurferOnWww 3,376 Reputation points
    2024-11-12T01:39:23.0366667+00:00

    trying to pass a list of data in a form from a view to mvc controller. there is no model for it

    You cannot obtain a list of data in the way you did in your code, i.e.,:

    var subjects = Request.Form["subjects"]; var creditUnits =Request.Form["creditunits"]; var gradePoint = Request.Form["gradepoints"];

    I recommend that you define a view model such like:

    Model

    namespace MvcNet8App.Models
    {
        public class Gpa
        {
            public string? Subject { get; set; }
            public string? Creditunit { get; set; }
            public string? GradePoint { get; set; }
        }
    }
    

    and use the view model in the controller to pass data between controller and view:

    Controller

    using Microsoft.AspNetCore.Mvc;
    using MvcNet8App.Models;
    
    namespace MvcNet8App.Controllers
    {
        public class CollectionController : Controller
        {        
            public IActionResult Index()
            {
                return View();
            }
            
            public IActionResult CalculateGpa()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult CalculateGpa(List<Gpa> gpa)
            {
                if (ModelState.IsValid)
                {
                    return RedirectToAction(nameof(Index));
                }
    
                return View();
            }
        }    
    }
    

    View

    Rewrite your view as shown below.

    Please note:

    • Do not use readonly attribute for the input element because it does not post the value to controller.
    • Assign index to name attribute of input elements such like name="[0].subject".
    • Names of name attribute (i.e., subject, creditUnit and gradePoint shown below) must match with the property names of Gpa class. They are not case-sensitive.
    @{
        ViewData["Title"] = "CalculateGpa";
    }
    
    <h1>CalculateGpa</h1>
    
    <form asp-action="CalculateGpa">
        <table>
            <tr>
                <td><input type="text" name="[0].subject" value="Maths" /></td>
                <td><input type="number" name="[0].creditUnit" placeholder="Credit unit" /></td>
                <td>
                    <select name="[0].gradePoint">
                        <option value="5"> A</option>
                        <option value="4"> B</option>
                        <option value="3"> C</option>
                        <option value="2"> D</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><input type="text" name="[1].subject" value="English" /></td>
                <td><input type="number" name="[1].creditUnit" placeholder="Credit unit" /></td>
                <td>
                    <select name="[1].gradePoint">
                        <option value="5"> A</option>
                        <option value="4"> B</option>
                        <option value="3"> C</option>
                        <option value="2"> D</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><input type="text" name="[2].subject" value="Chemistry" /></td>
                <td><input type="number" name="[2].creditUnit" placeholder="Credit unit" /></td>
                <td>
                    <select name="[2].gradePoint">
                        <option value="5"> A</option>
                        <option value="4"> B</option>
                        <option value="3"> C</option>
                        <option value="2"> D</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td><input type="text" name="[3].subject" value="Physics" /></td>
                <td><input type="number" name="[3].creditUnit" placeholder="Credit unit" /></td>
                <td>
                    <select name="[3].gradePoint">
                        <option value="5"> A</option>
                        <option value="4"> B</option>
                        <option value="3"> C</option>
                        <option value="2"> D</option>
                    </select>
                </td>
            </tr>
        </table>
        <button type="submit" name="GpaCalculator">Calculate GPA</button>
    </form>
    

    Result

    The following data,

    enter image description here

    are posted and properly passed to the argument of CalculateGpa(List<Gpa> gpa) as shown below:

    enter image description here

    0 comments No comments

  3. SurferOnWww 3,376 Reputation points
    2024-11-12T01:41:18.6666667+00:00

    This answer has been deleted because of duplication.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.