Add text in #Html.TextAreaFor MVC 4 - asp.net-mvc

I need to create the textarea field at my form
<textarea class="img-shadow" cols="20" id="Message" name="Message" rows="2">Message</textarea>
I write code
#Html.TextAreaFor(model => model.Message, new { #class = "img-shadow" })
but I get empty textarea without any text
<textarea class="img-shadow" cols="20" id="Message" name="Message" rows="2"></textarea>
How can I add text in?

The content of the text box will be whatever the value of model.Message is.
This should be set in your Action method in the Controller, and passed to the View
public ViewResult ActionName() {
var model = new ViewModel();
model.Message = "Text Area Content";
return View(model);
}
As a test just output model.Message in the View, it will be empty.
<p>#Model.Message</p>
Then #Html.TextAreaFor(model => model.Message, new { #class = "img-shadow" }) will output
<textarea class="img-shadow" cols="20" id="Message" name="Message" rows="2">Text Area Content</textarea>

After much scratching around I managed to get it done this way.
#{ var _address="Line 1\nLine 2\n Line 3"; }
#Html.TextArea(Model.xxxx , new { id="address" } )
<script>
var x = #Html.Raw(Json.Encode( _address )) ;
document.getElementById("address").value = x;
</script>
If you haven't any control characters like newline \n you can replace var x=#Html...... with var x = "Text" ;

#Html.TextAreaFor(model => model.Message, new { #class = "img-shadow", value = "added text" })
But If you initialize your model in controller Get method, then it will add text to your textarea, automaticly.
Check these tutorials

you add the default value into it.. by
#Html.TextAreaFor(model => model.Message, new { #class = "img-shadow",#value = "added text" })

In Controller Write
ModelVariable.Message= Server.HtmlDecode(ModelVariable.Message);
#Html.TextAreaFor(model => model.Message, new { #class = "img-shadow" })
It has worked for me

Related

html.TextAreaFor and HtmlDecode

question is very simple, I have this line of code within a template:
#Html.TextAreaFor(m => m.AnswerText, new { #class="Textarea", placeholder=Model.QuestionPlaceholder })
The problem is that sometimes AnswerText contains special characters like &, so I have tried the following:
#{var text = HttpUtility.HtmlDecode(Model.AnswerText); }
#Html.TextAreaFor(m => text, new { #class="Textarea", placeholder=Model.QuestionPlaceholder })
And now the problem is that I can see properly the text, but it doesn't save.
I also have tried the following:
#Html.TextAreaFor(m => HttpUtility.HtmlDecode(m.AnswerText), new { #class="Textarea", placeholder=Model.QuestionPlaceholder })
but I get the following error:
update: I have tried the following:
<div class="InputField">
#Html.TextAreaFor(m => m.AnswerText)
</div>
but when I try to save & and then go back to the page and have a look I see &
How do you do this? It is Blazor, Razor, MVC, within an InputField
I didn't like how I solved it, but it works. There is probably a better way:
#Html.TextAreaFor(m => m.AnswerText, new { #class = "Textarea " + Model.ID, placeholder = Model.QuestionPlaceholder })
<script>
var elements = document.getElementsByClassName("Textarea " + #Model.ID)[0];
elements.value = unescapeHtml(elements.value);
function unescapeHtml(value) {
return String(value)
.replace(/&/g, '&')...;
}</script>

Issue with asp-validation-for when used in a loop

I am having an issue with the asp-validation-for on a span element in the code below.
<div class="form-group">
#if (Model.Property.Options.ElementAt(i).OptionTypeId == PropertyOptionType.CheckBox)
{
var ItemChecked = (Model.Property.Options.ElementAt(i).OptionValue == "on") ? " checked" : "";
<text><input type="checkbox" class="form-check-input" name="Options[#i].Code" id="Options[#i].Code" #ItemChecked data-val="false" />
<label class="form-check-label" for="Options[#i].Value"> #(Model.Property.Options.ElementAt(i).OptionValue)</label></text>
}
else if (Model.Property.Options.ElementAt(i).OptionTypeId == PropertyOptionType.List)
{
<label class="control-label">
#Model.Property.Options.ElementAt(i).OptionValue
</label>
<select class="form-control" name="Options[#i].Code"></select>
}
<span class="text-danger field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Options.#(i).Code"></span>
When it is rendered in HTML it comes out as
<span class="text-danger field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Options.[3].Code"></span>
But no validation error messages ever land in the span. They are picked up in a page level validation summary when set to all so the unobtrusive code is all working correctly but the ID of the span is being broken by the square brackets.
Any ideas?
Thanks
Mark
To display Validation Summary, you need to include:
#Html.ValidationSummary(false/*excludePropertyErrors?*/, "", new { #class = "text-danger" })
To display field specific error message, you need to use ValidationMessageFor:
#Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentName, "", new { #class = "text-danger" })
See this tutorial
Don't manually generate the validation span, html helpers will do that for you... you would need something like this:
#for (int i = 0; i < Model.Property.Options.Count(); i++)
{
/* this one generates the input */
#Html.EditorFor(m => m.Property.Options[i], new { htmlAttributes = new { #class = "form-control" } })
/* this one generates the validation message */
#Html.ValidationMessageFor(m => m.Property.Options[i], "", new { #class = "text-danger" })
}

ASP.NET View IEnumerable Item validation

I have this ASP:NET MVC Razor View which has a IEnumerable as model .
I'm creating a table where each line represents a item from the IEnumerable.
I'm using this code:
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedFoo" value="#item.isAdded"
#(Html.Raw(item.isAdded? "checked=\"checked\"" : "")) />
#item.FooName
</td>
<td>
#Html.EditorFor(modelItem=> item.Name, new { htmlAttributes = new { #class = "form-control", style = "width: 70px" } })
#Html.ValidationMessageFor(modelItem=> item.Name, "", new { #class = "text-danger" })
</td>
</tr>
}
My problem is that when I enter an incorrect value for the "Name" property all the other text input get the validation error.
Solutions?
Thank you.
I would remove '#:' from the table elements. Also using the razor syntax I would generate a form tag. That may have something to do with it. Also add the ValidationSummary method.
Is that snippet you posted the complete view?
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "", new class{#class="text-danger"})
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedFoo" value="#item.isAdded"
#(Html.Raw(item.isAdded? "checked=\"checked\"" : "")) />
#item.FooName
</td>
<td>
#Html.EditorFor(modelItem=> item.Name, new { htmlAttributes = new { #class = "form-control", style = "width: 70px" } })
#Html.ValidationMessageFor(modelItem=> item.Name, "", new { #class = "text-danger" })
</td>
</tr>
}
}
If it's a partial view make sure the property 'Name' doesn't exist on any other fields in the view. 'Name' is very generic, perhaps you should rename it something more descriptive. 'FullName', 'ProductName'. ect....
Your foreach loop is generating duplicated name attributes for each textbox, and the ValidationMessageFor() applies to all elements with that name. In addition, you will never be able to bind to you model when you submit your form.
You need to use a for loop or custom EditorTemplate to generate your elements (refer this answer for more detail)
Assuming your model is IList<T>, then
#for(int i = 0; i < Model.Count; i++)
{
#Html.EditorFor(m => m[i].Name, new { htmlAttributes = new { #class = "form-control", style = "width: 70px" } })
#Html.ValidationMessageFor(m => m[i].Name, "", new { #class = "text-danger" })
}
In addition, use the CheckBoxFor() method to generate checkboxes (assumes selectedFoo is typeof bool)
#Html.CheckBoxFor(m => m[i].selectedFoo)
#Html.LabelFor(m => m[i].selectedFoo, Model[i].FooName)
This can be solved by creating another instance of the model solely for validation purpose in the view.
#{YourNameSpace.Models.Model ValidationModel = new YourNameSpace.Models.Model ();}
Than you can use it in the form like this:
<div class="form-group">
<input asp-for="#ValidationModel.PropertyName" name="[0].Name" class="form-control" />
<span asp-validation-for="#ValidationModel.PropertyName" class="text-danger"></span>
</div>
Or using HTML helper:
#Html.ValidationMessageFor(modelItem => ValidationModel.Name, "", new { #class = "text-danger" })

Editor Template for Enum with RadioButton not working

I updated a Enum Editor I found online to generate kendo radio controls instead of regular but the first radio button is generated with correct attributes and the remaining are wrong and at runtime, the whole set of radio buttons are not clickable
Here is the .cshtml for the editor:
#model Enum
#{
Func<Enum, string> getDescription = en =>
{
Type type = en.GetType();
System.Reflection.MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((System.ComponentModel.DataAnnotations.DisplayAttribute)attrs[0]).GetName();
}
}
return en.ToString();
};
var listItems = Enum.GetValues(Model.GetType()).OfType<Enum>().Select(e =>
new SelectListItem()
{
Text = getDescription(e),
Value = e.ToString(),
Selected = e.Equals(Model)
});
string prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
int index = 0;
ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
foreach (var li in listItems)
{
string fieldName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
<div >
#(Html.Kendo().RadioButton()
.Label(li.Text)
.Name(prefix)
.Value(li.Value)
.Checked(li.Selected)
.HtmlAttributes(new { #id = fieldName })
)
#*
This works properly
#Html.RadioButton(prefix, li.Value, li.Selected, new { #id = fieldName, #class = "k-radio" })
#Html.Label(fieldName, li.Text, new { #class = "k-radio-label" })
*#
</div>
}
ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
}
Here is the first radio on the form:
<div>
<input name="StaffType" class="k-radio k-radio" id="StaffType_0" type="radio" checked="checked" value="DACStaff" data-val-required="The StaffTypeEnum field is required." data-val="true">
<label class="k-radio-label" for="StaffType_0_DACStaff">DAC Staff</label>
</div>
And here is the next one:
<div>
<input name="StaffType" class="k-radio k-radio" id="StaffType_1" type="radio" value="AirportStaff">
<label class="k-radio-label" for="StaffType_1_AirportStaff">Airport Staff</label>
</div>
I see that the class tag k-radio is applied twice and except the first element has the data-* attributes but second radio button and onwards, the generated code is missing attributes.
Can someone point out why the generated code is not functioning?
Usage:
<div class="form-group">
#Html.LabelFor(m => m.StaffType, new { #class = "col-sm-3 control-label" })
<div class="col-sm-6">
#Html.EditorFor(m => m.StaffType, "RadioButtonListEnum")
</div>
</div>

Convert textbox type to password in asp.net mvc

How do I convert a textbox type to password in asp.net mvc?
Just write in Razor View i.e. in .cshtml file below line
#Html.PasswordFor(m=>m.Password)
Here m is model object and password is the password field name.
You mean <%=Html.Password("test")%>?
Either use the HTML helper function Password:
<%= Html.Password("Password") %>
or use the type parameter on an input field:
<input name="password" type="password" />
See listings 4 and 5 on this page
There are many types of using password-typed textboxes in ASP. NET MVC
With html controls it would be like;
<input type="password" name="xx" id="yy">
With Razor-syntax it would be like;
#Html.Password(name, value, html_attributes)
Or in a strongly typed view you could write
#Html.PasswordFor(model=>model.Password)
When using a strong-typed view and bootstrap, use the following code to make sure the password field is properly styled:
#Html.PasswordFor(model => model.Password, new { #class = "form-control" })
below is extention based on html helper:
before converting:
#Html.TextBox("mypass", null, new { style = "width: 200px;" })
After converting:
#Html.Password("mypass", null, new { style = "width:200px;" })
hope helps someone.
<div class="editor-field">
#Html.PasswordFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", placeholder = "Password" } })
#Html.ValidationMessageFor(model => model.Password)
</div>
In .cshtml file:
#Html.PasswordFor(modal => modal.Password)
Another way is to add #type = password to your html.texbox() attributes like so:
before converting:
#Html.TextBox("mypass", null, new { #class = "" })
After converting:
#Html.TextBox("mypass", null, new { #class = "", #type = password })
This will mask your text box text with circles instead of text. It does this, because the #type = password attribute tells your text box that it is of type "password".
This method of converting your text box to type password is an easy quick way to to make the conversion from your standard razor form text box.
#Html.EditorFor(model => model.Password,
"Password",
new { htmlAttributes = new { #class = "form-control" } })
Convert textbox type to password in asp.net mvc
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", placeholder = "Password", #type="Password" } })

Resources