html.TextAreaFor and HtmlDecode - asp.net-mvc

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>

Related

Telerik Grid: Handle click event on thick button within custom template opened on edit command

I am using a Telerik grid in an ASP.NET MVC view. I am completely new in Telerik.
My Telerik grid is as below:
#(Html.Telerik().Grid<MyDTOs.DetalleDTO>()
.Name("GridActividadesOferta")
.DataKeys(keys =>
{
keys.Add(d => d.indiceInterno).RouteKey("indiceInterno");
})
.Columns(columns =>
{
columns.Bound(cl => cl.nombreActividad).Title(Inspecciones.lblGridActividad.ToUpper()).ReadOnly(true).HtmlAttributes(new { #class = "actividad-column" });
columns.Bound(cl => cl.nombreSubActividad).Title(Inspecciones.lblGridSubActividad.ToUpper()).ReadOnly(true);
columns.Bound(cl => cl.articuloId).Title(Inspecciones.lblGridArticulo.ToUpper()).ReadOnly(true);
columns.Bound(cl => cl.CCAA_Expediente).Title("Expediente".ToUpper()).ReadOnly(false).Width(100);
columns.Bound(cl => cl.CCAA_Instalacion).Title("InstalaciĆ³n".ToUpper()).ReadOnly(false).Width(100);
columns.Bound(cl => cl.importeArticulo).Title("Importe".ToUpper()).ReadOnly(false).Width(100).Format("{0:c}").ClientFooterTemplate("<#= $.telerik.formatString('Total factura') #>");
columns.Bound(cl => cl.importeTasa).Title(Resources.Inspecciones.lblGridImporteTasa.ToUpper()).ReadOnly(false).Aggregate(aggr => aggr.Sum().Count())
.Width(100)
.Format("{0:c}")
//.ClientFooterTemplate("<#= $.telerik.formatString('{0:c}'," + Model.totalFactura + ")#>")
.ClientFooterTemplate("<#= '<span id=spanTotalFactura>' + $.telerik.formatString('{0:c}'," + Model.totalFactura + ") + '</span>' #>")
.Width(100)
.Format("{0:c}");
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Image);
commands.Delete().ButtonType(GridButtonType.Image);
}).Width(100).Visible(!ViewBag.readOnly);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("SelectGridVacias1", "Expedientes", new { ofertaComercialId = #Model.ofertaComercialId })
.Update("UpdateGridActividadesRegularizables1", "Expedientes", new { ofertaComercialId = #Model.ofertaComercialId })
.Delete("DeleteGridActividadesRegularizables1", "Expedientes", new { ofertaComercialId = #Model.ofertaComercialId })
;
})
.ClientEvents(events => events.OnDataBinding("onDataBindingArticulosGrid").OnDataBound("onDataBoundWrapper").OnEdit("onEditDatosArticulo")
.OnRowDataBound("onRowDataBound").OnDelete("onDelete").OnError("onErrorGrid"))
.HtmlAttributes(new { #class = "center-columns" })
.Selectable()
.Editable(editing =>
{
editing
.Mode(GridEditMode.PopUp)
.TemplateName("DatosArticuloTemplate1")
.InsertRowPosition(GridInsertRowPosition.Top);
})
)
As you can see above, I have two commands defined, Edit and Delete. The edit command button has a custom template specified in ".Editable". This template is called "DatosArticuloTemplate1" and it is as follows:
<div style="width:800px">
<div class="row-fluid">
<div class="span12">
#Html.Label("nombreArticulo", "Descripcion actual".ToUpper())
#Html.TextAreaFor(m => m.nombreArticuloFacturacion, new { style = string.Format("width:{0}px; ", 800) })
#Html.ValidationMessage("instalacionId")
</div>
</div>
<div class="row-fluid">
<div class="span2">
#Html.Label("importeArticulo", "Importe".ToUpper())
#(Html.Telerik().NumericTextBoxFor(model => model.importeArticulo).EmptyMessage("Importe").DecimalDigits(2).InputHtmlAttributes(new { style = "width:90px;" }))
</div>
<div class="span3">
#Html.Label("importeTasa", "Importe de tasa".ToUpper())
#(Html.Telerik().NumericTextBoxFor(model => model.importeTasa).EmptyMessage("Importe").DecimalDigits(2).InputHtmlAttributes(new { style = "width:90px;" }).Value(0))
</div>
<div class="span7">
#Html.Label("unidades", "InstalaciĆ³n".ToUpper())
#{Html.RenderAction("DropDownListInstalaciones", "SeleccionarInstalacionButton",
new
{
area = "",
clienteId = Model.OfertaComercial == null ? "" : Model.OfertaComercial.clienteId,
actividadId = Model.actividadId,
subActividadId = Model.subActividadId,
sociedadId = Model.OfertaComercial == null ? "" : Model.OfertaComercial.sociedadId,
dataBindTo = "instalacionId"
});
}
</div>
</div>
</div>
This custom template looks like this:
As you can see at the bottom left corner of the custom template, there are two buttons, one to validate the values introduced (thick button) and another to cancel. These buttons are from Telerik.
Now, I am trying to handle the click event on the thick button. Within the click event i want to validate the value introduced for "IMPORTE" field. If value introduced for this field is 0 then I want to popup a javascript alert modal window. This alert window must notify to the user that a value greater than 0 must be entered for that field. Also, custom template window "DatosArticuloTemplate1" must not be closed until user types in a correct value (value > 0) in the "IMPORTE" field. So how can I do it?

How to Change label value on drp selected change event in MVC

I have below code and I want to change label text base on selected role.
For example, If I select Admin then in label Text I need "Admin Name" etc.
I use below code but I is not working.
<div class="editor-field">
#Html.DropDownListFor(model => model.RoleID, new SelectList(ViewBag.RoleLsit, "Id", "RoleName"), "Select Category", new { onchange = "SelectedIndexChanged()" })
</div>
<div>
#Html.LabelFor(model => model.RoleName)
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<script type="text/javascript">
function SelectedIndexChanged() {
var sub = document.getElementsByName("RoleName");
sub.value = "Selected Role Name";
}
Thanks
You could find your elements using #Html.IdFor, if your js is in your view.
function SelectedIndexChanged() {
//find the label
var label = document.querySelector('label[for="#Html.IdFor(m => m.RoleName)"]');
//get the dropDown selected option text
var dropDown = document.getElementById("#Html.IdFor(m => m.RoleId)");
var selectedText = dropDown.options[dropDown.selectedIndex].text;
//set the label text
label.innerHTML=selectedText
}
By the way, taking a look a jQuery might be an "interesting" option.
You could simply remove the new { onchange = "SelectedIndexChanged()" , then
$('##Html.IdFor(m => m.RoleId)').change(function() {
$('label[for="#Html.IdFor(m => m.RoleName)"]').text($(this).children('option:selected').text());
});
function SelectedIndexChanged() {
document.getElementsById("RoleName").InnerHtml="Role name goes here";
}
you should use get element by id instead of name because when this html helper renders the strongly typed binded attributes becomes the id of that control . so in your case role name will be the ID

MVC 4 dropdownlist in edit form doesnt give the correct value after edit command from grid

This is very weird and i know that this worked in the past. I must have broken it with something else but I really don't know what.
I'm a .NET programmer with very little MVC knowledge and it seems that I'm missing some key things here , that mvc does in the background.
Let met explain it as best as I can.
I have a view, which contains this :
<tbody>
#foreach (var experienceViewModel in this.ViewData.Model)
{
var id = "GetExperienceDetail" + experienceViewModel.Id;
<tr>
<td>#experienceViewModel.Assessment</td>
<td>#experienceViewModel.CompanyName</td>
<td>#experienceViewModel.Description</td>
<td>#experienceViewModel.StartDate</td>
<td>#experienceViewModel.EndDate</td>
<td width="20"><i class="glyphicon glyphicon-pencil"></i></td>
<td width="20"><a id="#Html.Raw(id + "delete")" class="confirm-delete" data-keyname="experienceId" data-textfield="#string.Concat(experienceViewModel.Assessment, " | ", experienceViewModel.Description)" data-link="#Html.Raw(id + "delete")" data-key="#experienceViewModel.Id" data-controller="Experience" data-action="ExperienceDelete" href="#" title="Verwijder"><i class="glyphicon glyphicon-remove"></i></a></td>
</tr>
}
Its not the last tr but the one before that. The one with openDetail. This function will be called from the js web.js which I'm gonna paste below:
function openDetail(link) {
var $link = $('#' + link);
debugger;
var controller = $link.attr('data-controller');
var action = $link.attr('data-action');
var id = $link.attr('data-key');
var form = $link.attr('data-form');
var modelName = $link.attr('data-model');
//default person
if (modelName == null)
modelName = "person";
modelName = modelName.toLowerCase();
var valueModel = $link.attr('data-' + modelName);
var json = "{\"id\" : " + id + ", \"" + modelName + "\"" + " : " + valueModel + "}";
var url = '/' + controller + '/' + action;
$.ajax({
url: '/' + controller + '/' + action,
type: 'POST', // not sending json over url
data: json,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#partialoveview').html(data);
if (typeof form !== 'undefined' && form !== false) {
$.validator.unobtrusive.parse($('#' + form));
$("span.field-validation-valid").hide();
$('.label-error').hide();
}
loadForm();
},
error: function (data) {
}
});
This function does the job, the only thing that is going wrong is that dropdownlist, and specifically THAT one cause there is another one, below it , and this has the correct behavior of selecting the value that it has ...
This will go to the Person controller with the action ExperienceDetail(int id, int person)
[HttpPost, OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
public PartialViewResult ExperienceDetail(int id, int person)
{
var experienceViewModel = new ExperienceViewModel { AssessmentList = this.AssessmentList(), CompanyList = this.CompanyList(), PersonId = person };
if (id > 0)
{
Data.Model.Experience experience = this._experienceRepository.GetExperienceDetail(id);
experienceViewModel = new ExperienceViewModel(experience) { AssessmentList = this.AssessmentList(), CompanyList = this.CompanyList()};
}
return this.PartialView("_ExperienceDetailPartial", experienceViewModel);
}
this.CompanyList gets a select list from the basecontroller
When this view is returned , i cant see that this select list has a selectedvalue. But then again, the ddl which is working has also a null at the selectedvalue so this isn't responsable for setting the correct value after edit I guess?
Then the detail screen , which is put into a div from the js:
I only put in the beginning with first the company drop down ( NOT WORKING ) and then the assessment ddl ( WORKING )
#model Emenka.HumanResources.Application.Models.ExperienceViewModel
#using (Html.BeginForm("UpdateExperienceDetail", "Person", FormMethod.Post, new { #id = "ExperienceDetail", #role = "form", data_action = "ExperienceOverview", data_controller = "Person" }))
{
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.PersonId)
<fieldset>
<legend>Ervaring</legend>
<div class="row">
<div class="col-md-5">
<div class="form-group">
#Html.LabelFor(m => m.CompanyId, new { #class = "control-label" })
<div class="input-group col-xs-9">
#Html.DropDownListFor(m => m.CompanyId, ViewData.Model.CompanyList, string.Empty, new { #class = "no-focus form-control" })
#* #Html.ValidationMessageFor(m => m.CompanyId, " ")*#
...
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.AssessmentId, new { #class = "control-label" })
#Html.DropDownListFor(m => m.AssessmentId, ViewData.Model.AssessmentList, string.Empty, new { #class = "no-focus control-sm-7 form-control" })
#* #Html.ValidationMessageFor(m => m.AssessmentId, " ")*#
</div>
<div class="form-group">
#Html.LabelFor(x => x.StartDate, new { #class = "control-label" })
<div class="input-group col-xs-7">
#Html.TextBoxFor(x => x.StartDate, new { #class = "form-control date-picker", #readonly = "readonly" })
<label for="StartDate" class="input-group-addon glyphicon glyphicon-calendar add-on" />
</div>
</div>
I've searched and searched and i just have no clue what to search for . Can you guys give me tips plz ?
PS : dont mind the spaces at the data attrib, i was trying to get rid of the error when submitting this form at stackoverflow ( code 4 spaces ) .
i know the third parameter from the drop down is to select the default value, but this is string.Empty with the dropdownlist of assessment and this gets the correct value when clicking edit, and so not an empty string like the company dropdown... so logically this cannot be the problem
i found the problem !
Setting the viewdata property of the corresponding companyId which was linked to the dropdown, solved all my problems. I dont know why this worked at the other pages, maybe i just missed it .

Add text in #Html.TextAreaFor MVC 4

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

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