I have an issue which I've solved, but I don't understand why I've solved it.
I'm using MVC, and posting in a form using razor.
My Email model contains many properties but the important one to note is
public class MyEmail
{
public string Email { get; set; }
}
And the controller signature is
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult Contact(MyEmail Email)
{
ViewBag.Message = $"Email is null : {Email == null}";
return View();
}
Please note, both the property of MyEmail
is Email
and the parameter in the Controller
is also named Email
When I post in the CSHTML (view), the controller's parameter email
is always null
.
I've played with this and learned the issue is the parameter name (email) matches the name of a property in my object.
Why is this not allowed? Meaning does any one know what MVC is doing behind the scenes which confuses it?
By changing the property from Email
to EmailAddress
or changing the parameter name from Email
to MySendObject
resolves the issue. I don't understand why though.
The view is
@model WebApplication1.Models.MyEmail
@{
ViewBag.Title = "Contact";
}
@using (Html.BeginForm())
{
@Html.TextBoxFor(a => a.Email);
<input type="submit" value="Send" />
}