Text area not binding correctly to model in .net core

I have a model with multiple fields in a .net core web app.

The model is bound to a view, which uses asp-for tag helpers to render hidden inputs, text inputs, select lists and a text area.

The issue..

On posting to the server, all inputs are bound correctly, except the text area. This is always coming through as null.

Even more strangely, if I assign a value to the text area property before rendering the view, the value displays in the text area as expected (not the strange bit), and when posted to the server, the value is posted back. If I try and change the value however, the original one is still picked up in the model binding, despite Chrome showing in the network tools that the new value was what was posted.

Has anyone else experienced anything like this? Am I being an idiot (again)?

A sub set of my code below:

Render View:

public IActionResult Review()
{
    var requestVm = new Request();

    requestVm.AdditionalComments = "This was set in the model before rendering the view and should be overwritten.";
    return View(requestVm);
}

Html:

@model Models.Request
<form asp-controller="Request" asp-action="Review" method="post" role="form" enctype="multipart/form-data" class="ui form review">
<textarea asp-for="AdditionalComments" class="AdditionalComments"></textarea>
</form>

Post Action:

[HttpPost]
public IActionResult Review(Request requestVm)
{
    // Some logic in here to save to db etc..
    return RedirectToAction("Thank_You");
}

As you can see, nothing special going on there.

Any help appreciated.

Mark


Please use Bind(Include=string) attribute in the post method and mention all the property names including the one that gets missing. This demonstrates the use of the attribute:

[HttpPost]
public IActionResult Review([Bind(Include = "AdditionalComments,other properties")] Request requestVm)
{
    // Some logic in here to save to db etc..
    return RedirectToAction("Thank_You");
}

Let me know if this doesn't help.


As I rather suspected, there was in fact nothing wrong with the code..

Instead, there was a legacy hidden input for the same property being added to the page via a partial from a much earlier stage in the project before various design changes. It explains why setting a value on load was being carried through, and updating in the text are was never working, as the model was simply binding to the first instance of the property found.

Had to be something simple.. Hopefully, this will help anyone else who finds themselves in a similar situation.

链接地址: http://www.djcxy.com/p/53974.html

上一篇: 从商业帐户创建和管理Facebook应用程序

下一篇: 文本区域无法正确绑定到.net内核中的模型