Saturday, February 29, 2020

MVC Core ViewBag and Request.Form

ViewBag is a method to pass data from Controller to View.

Request.Form is the method to extract the value of an html control.


public IActionResult Index()
  {
            return View();
  }

  [HttpPost]
  public IActionResult Index(string str)
  {
      //ViewBag.Hello = "Hello " + Request.Form["Name"] + " located at " + Request.Form["Location"];
        ViewBag.Hello = $"Hello {Request.Form["Name"]}  located at {Request.Form["Location"]} specializing in {Request.Form["Spec"]}";
            return View();
   }

@ViewBag.Hello

<form method="post" asp-controller="Home" asp-action="Index">
    <div>
        Name 
        <input type="text" name="Name"  />
    </div>
    <div>
        Location
        <input type="text" name="Location"  />
    </div>
    <div>
        Specialization
        <select id="Spec" name="Spec">
            <option value=".Net">.Net</option>
            <option value=".Net Core">.Net Core</option>
        </select>
    </div>
    <input type="submit"/>
</form>

No comments:

Post a Comment