I am very new to C#. I am just trying to get an MVC form to work to understand how information is passed from the view to controller. I am trying to submit my form and have the page updated with the input ( eventually so I can figure out how to pass the form data to an XML file. But I get an error when I hit submit on the form. Need some help please. I can't find a simple tutorial to walk me through this.
My files are : User.cs ( model), AddACustomerController.sc ( controller), and AddACustomer.cshtml ( view)
MODEL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace WebApplication10.Models
{
public class User
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
}
}
CONTROLLER:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Web;
using WebApplication10.Models;
namespace WebApplication10.Controllers
{
public class AddACustomerController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UserForm(Models.User person)
{
string firstname = person.FirstName;
string lastname = person.LastName;
string role = person.Role;
ViewBag.n = person.FirstName;
ViewBag.l = person.LastName;
ViewBag.r = person.Role;
return View("UserForm");
}
}
}
VIEW:
@model WebApplication10.Models.User
@{
ViewData["Title"] = "AddACustomer";
}
<h1>AddACustomer</h1>
<h4 style="color:purple">
<b>First Name:</b> @ViewBag.f <br />
<b>Last Name:</b> @ViewBag.l <br />
<b>Role:</b> @ViewBag.r
</h4>
<hr />
@using (Html.BeginForm("UserForm", "AddACustomer", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
</tr>
<tr>
<td>First Name: </td>
<td>
@Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
@Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Role: </td>
<td>
@Html.DropDownListFor(m => m.Role, new List<SelectListItem>
{ new SelectListItem{Text="Administrator", Value="Administrator"},
new SelectListItem{Text="Data Entry", Value="Data Entry"},
new SelectListItem{Text="Sales", Value="Sales"},
new SelectListItem{Text="Networking", Value="Networking"}
}, "Please select")
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
PICTURE OF VIEW:
PICTURE OF ERROR WHEN I HIT SUBMIT BUTTON ON FORM:


The issue is
It is probably easiest for you to just keep all your routes called Index. You can have
Otherwise you'll need to create another .cshtml (View) called UserForm.cshtml.