We are migrating our project from .net Framework 4.72 to .net core 3.1.
I have next html helper code:
@Html.TextBoxFor(Model => Model.Property, "{0:0}", htmlAttributes: new { maxlength = 8, Name = "Model2.Property" })
But when I inspect html code, name attribute is not overridden. How can I override it? Thank you.
You can use TextBox
:
@Html.TextBox("Model2.Property",Model.Property,new { maxlength = 8})
or use asp-for
and name
:
<input asp-for="@Model.Property" name="Model2.Property" maxlength="8"/>
Pass data with prefix in form,and validate it in the action(ModelState.IsValid'),then return the error message to your view,but i think it's not a good idea,i think you don't need prefix in you controller action:
Here is a demo:
TestController:
public IActionResult TestPrefix([Bind(Prefix = "Model2")]DataModel model) {
if (ModelState.IsValid) {
return Ok("success");
}
string message=string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => !string.IsNullOrWhiteSpace(x.ErrorMessage) ? x.ErrorMessage : x.Exception.Message.ToString()));
return Ok(message);
}
public IActionResult TestDataModel() {
return View();
}
TestDataModel.cshtml:
<form method="post">
@Html.TextBoxFor(Model => Model.Property, "{0:0}", htmlAttributes: new { maxlength = 8 })
<div style="color:red" id="errormessage">@TempData["Error"]</div>
<button onclick="postModel()">post</button>
</form>
@section scripts{
<script type="text/javascript">
function postModel() {
var formdata = new FormData();
formdata.append("Model2.Property", $("#Property").val());
$.ajax({
type: "POST",
url: '@Url.Action("TestPrefix", "Test")',
contentType: false,
processData: false,
data: formdata,
}).done(function (data) {
//$("#errormessage").append(data);
});
}
</script>
}
DataModel:
public class DataModel
{
[Required]
[Range(0,5)]
public int Property { get; set; }
}