Transfer data from view to controller

Ted 1 Reputation point
2022-05-08T11:46:00.68+00:00

Hello! I am quite new to .Net MVC and building a web app for the first time looking for some better explained processes.

I am trying to get a string input from a view (index) to a controller (home controller). Through a little research I can see this is usually done by something called a "Model" where essentially you would store the data from the view, INTO the model and then, in the controller it takes that model as a parameter and you are able to use it. While this process sounds great I have been unable to do it.

Here is my index.cshtml page:

@using RequestPrototype.Models

<table class="table small">

            <tr>
                <td>
                    <label>Enter Ticker</label> <input type="text" asp-for="Ticker" class="form-control" />
                </td>
                <td style="vertical-align: bottom; horiz-align: center">  <button asp-controller="Home" asp-action="Index" class="btn btn-dark">Search</button></td>
            </tr>
        </table> 

My userInput.cs model:

namespace RequestPrototype.Models
{
    public class userInput
    {
        // holds the user response from the index page
        public string? Ticker { get; set; }
    }
}

Lastly my HomeController.cs:

using RequestPrototype.Models;

namespace RequestPrototype.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index(userInput input)
        {
                 String ticker = input.Ticker;
                 return View();
            }

        }
    }
}

I'd also be interested as to how you could then return data from a controller to a view using a different model than the input one? Also, I'm using .NET 6 if that was important.
Thank you for reading!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,573 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 65,576 Reputation points
    2022-05-08T15:42:00.623+00:00

    Views pass data to controller in one of two ways (ignoring JavaScript ajax calls).

    1. An anchor (<a>) where the data is passed as query string name/value parameters. The mvc data binding will bind the parameters to the controllers action parameters by name.
    2. A form post. The form data is again passed as names / value pairs. Again the form element name must match the models property name to bind to.

    In your case you appear to want to do the second case, but did not define a form in the view.

    When a submit button is clicked, only the form elements in the same form as the submit button are posted. Also a page can have many forms, but only one form and it’s elements can be posted.

    0 comments No comments

  2. Zhi Lv - MSFT 32,336 Reputation points Microsoft Vendor
    2022-05-09T08:10:35.7+00:00

    Hi @Ted ,

    As Bruce-SqlWork said, to pass data from view to the controller, we need to add the data to the request URL (use the query string, then the request URL like this: /Home/Index?Ticker=AAA) or submit a form (use the <form> tag).

    General, in the index page, it will use the display a list of userInput, then, if you also want to create new userInput, you could use a <form> tag to submit a form to insert new records.

    The Index.cshtml like this: Note: At the top of the page, we are using an IEnumerable or List type to receive the returned model from the action. Then in the form tag, we are using an input element with the name Ticker, after submitting the form, in the action method, it will get the value via the name attribute.

    @model IEnumerable<WebApplication2.Models.userInput>  
      
    @{  
        ViewData["Title"] = "Index";  
    }  
      
    <h1>Index</h1>  
      
    <div class="row">  
        <div class="col-md-4">  
            <form asp-action="Index">  
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
                <div class="form-group">  
                    <label class="control-label">Ticker</label>  
                    <input name ="Ticker" class="form-control" />   
                </div>  
                <div class="form-group">  
                    <input type="submit" value="Create" class="btn btn-primary" />  
                </div>  
            </form>  
        </div>  
    </div>  
    <table class="table">  
        <thead>  
            <tr>  
                <th>  
                    @Html.DisplayNameFor(model => model.Ticker)  
                </th>  
                <th></th>  
            </tr>  
        </thead>  
        <tbody>  
    @foreach (var item in Model) {  
            <tr>  
                <td>  
                    @Html.DisplayFor(modelItem => item.Ticker)  
                </td>  
                <td>  
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |  
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |  
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>  
                </td>  
            </tr>  
    }  
        </tbody>  
    </table>  
    

    Then, the controller like this:

    public class RequestPrototypeController : Controller  
    {  
        private readonly ApplicationDbContext _dbcontext;  
        public RequestPrototypeController(ApplicationDbContext applicationDbContext)  
        {  
            _dbcontext = applicationDbContext;  
        }  
        public IActionResult Index(string Ticker)  
        {  
            if (!string.IsNullOrEmpty(Ticker))  
            {  
                //if tricker is not null, insert the value into database.  
                _dbcontext.UserInput.Add(new userInput() { Ticker = Ticker });  
                _dbcontext.SaveChanges();  
            }  
               
            //define a list to store the latest data.  
            var items = new List<userInput>();    
            //get the latest  data from database.  
            items = _dbcontext.UserInput.ToList();  
    
            //return the data to the view page.  
            return View(items);  
        }  
    

    Then, the output like this:

    200156-1.gif

    Besides, you can also create a Create page to create the new item, then the Create page like this:

    Create.cshtml: Note: in this page, the page model is userInput, and we can use asp.net core tag helper to bind property

    @model WebApplication2.Models.userInput  
      
    @{  
        ViewData["Title"] = "Create";  
    }  
      
    <h1>Create</h1>  
      
    <h4>userInput</h4>  
    <hr />  
    <div class="row">  
        <div class="col-md-4">  
            <form asp-action="Create">  
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
                <div class="form-group">  
                    <label asp-for="Ticker" class="control-label"></label>  
                    <input asp-for="Ticker" class="form-control" />  
                    <span asp-validation-for="Ticker" class="text-danger"></span>  
                </div>  
                <div class="form-group">  
                    <input type="submit" value="Create" class="btn btn-primary" />  
                </div>  
            </form>  
        </div>  
    </div>  
    

    The Create action methods:

        public IActionResult Create()  
        {  
            return View();  
        }  
        [HttpPost]  
        public IActionResult Create(userInput userInput)  
        {  
            //check whether the model is valid or not  
            if (!ModelState.IsValid)  
            {  
                //if not valid, return to the create page with the userinput model  
                return View(userInput);  
            }  
    
            //if model is valid, insert the data into database.  
            _dbcontext.UserInput.Add(new userInput() { Ticker = userInput.Ticker });  
            _dbcontext.SaveChanges();  
            //redirect to the index action to display the latest data.  
            return RedirectToAction(nameof(Index));  
        }  
    

    Then, the output like this:

    200202-2.gif

    More detail information, refer the following tutorials:

    Part 6, controller methods and views in ASP.NET Core

    Views in ASP.NET Core MVC

    Tutorial: Implement CRUD Functionality - ASP.NET MVC with EF Core


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    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.