Eric Lam Eric Lam - 3 years ago 145
C# Question

Form binding giving null properties

I have tried a couple of ways to deal with try fixing the problem like

Default Binder problem: https://stackoverflow.com/a/37601937/4444304

And non of them have worked...
This is obviously not nested too. Which most of them are caused by nested problems...

Form.Request is getting the submitted parameters. Just the model does not seems to assign :s

Which is more weird, the field is marked as required. But the Model state is returned as Valid too.

I can't really see I can find or do further more... Thanks.

My Model looks like this

EmailSubmitModel.cs

using System.ComponentModel.DataAnnotations;

namespace myapp.Models.Home
{
public class EmailSubmitModel
{
[Required(ErrorMessage = "Please enter your name")]
public string FriendName;
}
}


HomeController.cs

using myapp.Models.Home;

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Submit(EmailSubmitModel emailSubmitModel)
{
if (ModelState.IsValid)
{
return Json(emailSubmitModel);
}
return View(emailSubmitModel);
}


index.cshtml

@using myapp.Models.Home
@model EmailSubmitModel
<form asp-controller="Home" asp-action="Submit" method="post">
<div asp-validation-summary="All"></div>
<label asp-for="FriendName">@Localizer["Friend's Name"]</label>
<input asp-for="FriendName" type="text" />
<span asp-validation-for="FriendName"></span>
<input type="submit" class="btn btn-warning">@Localizer["Send the email"]</button>
</form>

Answer Source

Firstly you need to set the name attribute that will be used in the Model-Binder:

<input asp-for="FriendName" name="FriendName" type="text" />

And secondly the FriendName should be declared as property. It currently is a field:

public string FriendName { get; set; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download