Thursday, July 13, 2023

ASP.NET Core - Different approaches to send data from View to Controller

ASP.NET Core provides different techniques to send data from form to controller. Some important ones are as follows.
  1. Request.Form["form-control-name"] in action method body.
  2. Parameter binding: The form name parameter binding with action method parameter.
  3. FromFormAttribute as action parameter.
  4. BindPropertyAttribute: The form name parameter binding with a property of controller class.
  5. BindPropertiesAttribute The form name parameters binding with different properties of controller class. 
  6. IFormCollection as action parameter.
  7. Model: Create a model and pass it parameter to the action method.
  8. TryUpdateModelAsync: In this case, we use create a model and pass it as parameter to UpdateModel (model) method. The UpdateModel method is called in the action method body.
We illustrate them in the following examples.
Open the Visual Studio and create web project using ASP.NET Core Web App (Model-View-Controller) template. 
Project name: FormDataAccess
Solution name: FormDataAccess
.NET Core version: 5.0
When application is created, clear the Views/Home/Index view.cshtml content and paste the following code to create form.

@{
    ViewData["Title"] = "Home Page";
}
<form method="post" >
    <div class="row">
        <div class="container">
            <div class="col-md-4">
                <div form-group">
                    <label class="col-form-label" for="name">Name</label>
                    <input class="form-control" type="text" name="name" id="name" />
                </div>
                <div class="form-group">
                    <label class="col-form-label" for="age">Age</label>
                    <input type="text" class="form-control" name="age" id="age" />
                </div>
                <div class="form-group">
                    <button class="btn btn-primary" type="submit" value="">Send Data</button>
                </div>
            </div>
        </div>
    </div>
</form>

1. Request.Form["form-control-name"] in action method body


using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [ActionName("Index")]
        [HttpPost()]
        public IActionResult Index2()
        {
            string name1 = Request.Form["name"];
            // Request.Form returns string type data
            string age1 = Request.Form["age"];
            return RedirectToAction("Index");
        }
    }
}

2.  Action Parameters: The form name parameter binding with action method parameter


using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index(string name, int age)
        {
            string name1 = name;
            int age1 = age;
            return RedirectToAction("Index");
        }
    }
}

3. FromFormAttribute with  Action Parameter

using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index([FromForm] string name, [FromForm] int age)
        {
            string name1 = name;
            int age1 = age;
            return RedirectToAction("Index");
        }
    }
}

4. BindPropertyAttribute on a property of controller: The form name parameter binding with a property of controller class


using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        // create properties matching form name parameters and apply BindProperty attribute
        [BindProperty]
        public string name { get; set; }
        [BindProperty]
        public int age { get; set; }

        [HttpPost]
        [ActionName("Index")]
        public IActionResult Index3()
        {
            string name1 = name;
            int age1 = age;
            return RedirectToAction("Index");
        }
        public IActionResult Index()
        {
            return View();
        }
    }
}

5. BindPropertiesAttribute on controller: The form name parameters binding with different properties of controller class

using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    [BindProperties]
    public class HomeController : Controller
    {
        // create properties matching form name parameters and apply BindProperties attribute on controller class 
        public string name { get; set; }
        public int age { get; set; }

        [HttpPost]
        [ActionName("Index")]
        public IActionResult Index3()
        {
            string name1 = name;
            int age1 = age;
            return RedirectToAction("Index");
        }
        public IActionResult Index()
        {
            return View();
        }
    }
}

6. IFormCollection as  Action Parameter: Look at the image also given below.


using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index(IFormCollection keyValues)
        {
            var name = keyValues["name"];
            var age = keyValues["age"];
            var count = keyValues.Count;
            return RedirectToAction("Index");
        }
    }
}

7. Model as Action Parameter: In this case we create a model class and pass it as parameter to the action method. The name of model parameters must match the form name parameters.


using FormDataAccess.Models;
using Microsoft.AspNetCore.Mvc;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index(Person person)
        {
            var name = person.Name;
            var age = person.Age;
            return RedirectToAction("Index");
        }
    }
}
8. TryUpdateModelAsync in  Action Body: In this case we create a model class and pass it as parameter to the UpdateModel method. The UpdateModel is used in the action method body in try-catch block. You can otherwise use TryUpdateModel as well.

using FormDataAccess.Models;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace FormDataAccess.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [ActionName("Index")]
        public async Task Index4()
        {
            try
            {
                Person person = new Person();
                await TryUpdateModelAsync(person);
                var name = person.Name;
                var age = person.Age;
                RedirectToAction("Index");
            }
            catch (System.Exception)
            {
                return View();
            }

            return RedirectToAction("Index");
        }
    }
}

Updated on 13 July 2023

No comments:

Post a Comment

Hot Topics