ASP.NET MVC 3: Override name attribute with TextBoxFor
Rob, actually there is a much simpler way. Instead of name, use Name:
@Html.TextBoxFor(x => x.Data, new { Name = Model.Key + "_Data", id = Model.Key + "_Data" })
No opportunity to override name attribute for @Html.TextBoxFor in asp.net core 3.1
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; }
}
result:
MVC2: Impossible to change the name with TextBoxFor?
You can't use the strongly typed lambda version for this, you'd need to use the older version
Html.TextBox("txt1",new {@id = "txt1"})
Custom attribute with dash in name using EditorFor/TextBoxFor/TextBox helpers
Thanks to Crescent Fish above, looks like you can just use underscores and MVC 3 will convert them to dashes since underscores aren't allowed in HTML attribute names.
set id and name for @HtmlEditorFor?
EditorFor
does not allow for adding htmlAttributes. For the specific types of editors you'll have to use TextBoxFor
(or whatever type you're using).
@Html.TextBoxFor(m => m.value, new { id = "testid1", name="Testname1" })
You can also create a custom editor template for the particular type you're creating an editor for.
override the id attribute of Html.EditorFor - not working
Sorry, i should've looked more carefully. You don't want quotes around @idPasswordTextBox in your TextBoxFor method. That is run on the server, so when you put quotes around the name it is being treated as a literal string. Remove the quotes, and remove the @ sign in front of id, and it will work.
Its important to always remember what is running on the server, and what is running on the client.
@Html.TextBoxFor(model => model.Password, new { id = @idPasswordTextBox })
Is it possible to override names of model bound elements with attributes?
Do standard helpers support any attribute whcih allow abstract from model member names?
No, they don't. You could write a custom model binder or simply name the properties of the view model as expected.
Related Topics
How to Find the Mode in Array C#
What Is a Regular Expression for Parsing Out Individual Sentences
Is the Size of a Form in Visual Studio Designer Limited to Screen Resolution
How to Resize Image in C# Winrt/Winmd
How to Get Property Change Notifications with Ef 4.X Dbcontext Generator
Removing Dynamically Created Controls in C#
Does Garbage Collector Call Dispose()
How to Suppress a Stylecop Warning
C# Static Member "Inheritance" - Why Does This Exist at All
Converting String Format to Datetime in Mm/Dd/Yyyy
Parsing Performance (If, Tryparse, Try-Catch)
Using SQLdataadapter to Insert a Row
Object Reference Not Set to an Instance of an Object
Dbcontext Discard Changes Without Disposing
Read Binary File into a Struct
Workaround for the Waithandle.Waitall 64 Handle Limit
Best Way to Take Screenshots of Tests in Selenium 2
How to Download a Nuget Package Without Nuget.Exe or Visual Studio Extension