It is the first time that I use Kendo and I am quite lost, in this case I have a grid in the form of a table and there are fields that I do not show with ClientTemplate and depending on whether the ServiceStatusId field returns 5 I have to cross out the text and if not, leave it as it is. But I try to put a conditional for the case of the style and it doesn't work for me. I have tried several ways and I can't find a way to make a conditional to evaluate that. If I put it this way it will let me, but I need to indicate the conditional
style = "text-decoration:line-through;"
And this is how I have it right now:
<div>
#(Html.Kendo().Grid<Faculty.Web.Models.Ces.MyTasksProgramFilterViewModel>
()
.Name("program_session_services_grid")
.AutoBind(true)
.Columns(columns =>
{
columns.Select().Width(50)
.HeaderHtmlAttributes(new { #class = "grid_SelectColumn" })
.HtmlAttributes(new { #class = "grid_SelectColumn" });
columns.Bound(c => c.ProviderLiteral).HtmlAttributes(new { #class = "Assignment_Courses_Grid_Item_Center FontSize10 ", style = $"\\# if (ServiceStatusId==5) {{ \\# '" + "text-decoration:line-through;" + "' \\# }} \\#" })
.Title(Resources.Ces.MyTasksPrograms_Grid_Header_Provider)
.HeaderHtmlAttributes(new { #class = "Assignment_Courses_Grid_Header_Center " });
Any suggestion, help or advice is good for me, I already tell you that I have never touched Kendo until now and I need to apply this conditional and I don't know how to do it so that it detects it correctly and works.
No you can't use a template in the .HtmlAttributes. There's a few different ways you can solve this.
Probably the best way is to apply a template on the content.
columns.Bound(c => c.ProviderLiteral).ClientTemplate($"#=GetKendoTemplate(data,'ProviderLiteralTemplate')#");
Where GetKendoTemplate is a javascript method
function GetKendoTemplate(data, templateName) {
var templateObj = $('#' + templateName).html();
var template = kendo.template(templateObj);
return template(data);
}
And ProviderLiteralTemplate is a kendo template
<script id="ProviderLiteralTemplate" type="text/x-kendo-template">
<div style="# (ServiceStatusId==5) ? 'text-decoration:line-through;' : ''">
<span>#=ProviderLiteral#</span>
</div>
</script>
Related
I'm using kendo grid and editor template for showing my data. in editor I've given id to DataValueField() and name to DataTextField() of kendo dropdown list. In change event, I'm not able to get the DataValueField(). see the following code
This is my editor template MemoCarrier.chtml
#using System.Collections
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
.Events(e =>
{
e.Change("MemoCarrier");
})
)
Here is my on change function
function MemoCarrier(e) {
var AirlineName = this.value();
alert(AirlineName) //it displays PARTNERNAME instead of PARTNERID
}
Currently I'm getting name ie;DataTextField() value. instead of that, I need DataValueField().
Thanks for suggestions in advance!
so based on your comment the easiest way to do this would probably use the data-bind attribute to simplify the process of binding the model. Assuming you are using the MVC helper for the grid as well.
so taking your code and adding this:
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum", data_bind="value:{yourProperyNameHere}" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
)
So hopefully you can see all I am doing is adding a new HtmlAttribute property to the control for you. All you need to do is put whatever property is meant to be the value for this.
Depending on if this value is a complex (object) or simple (string, int etc) primitive type you may need to set the Primitive property to true so that only the valuefield e.g the id you are assigning is bound back to the grid's row model.
I am having a Controller Calculations where I have a property called Formula. The main idea behind the Calculation is to perform operations using objects from other tables in the Database , here for instance SetValues.
What I am trying to achieve
I have a textbox for entering the Formula. I want to make sure that the variables used in the Formula are existing in the database. I can display the names of all the available rows in the table SetValues. I would like to make the values being displayed from the Setvalues click-able so that the value being clicked would be displayed on the textbox. I will keep a table with the mathematical operators as well which would also work in the same way. How can I make the TextBox for Formula the way I want? And how can I make the Names to be entered into the TextBox when clicked.
When the formula has been saved I want to use the formula to perform calculations based on the values of the SetValues(Assume SetValue has properties Name and Values(int)). I understand that I need to parse the Formula to perform the calculation which I have not yet tried, but could find other examples where the same has been performed. I have done something similar but with a Calculation string with numbers alone. I have not done something that would parse a formula and then assign values to it. Is it possible to achieve the parsing?
Calculation View
#foreach(var item in ViewBag.SetValues
{
<p>#item.Name</p>
}
#Html.LabelFor(model => model.CalculationName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.CalculationName, new { htmlAttributes = new { #class = "form-control" } })
#Html.LabelFor(model => model.CalculationFormula, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.CalculationFormula, new { htmlAttributes = new { #class = "form-control" } })
<input type="submit" value="Create" class="btn btn-default" />
In a ViewBag I have passed the SetValue and the elements are displayed.
The Model classes and Controller are not relevant for the output I guess. But if it is required comment. Further details can be added.
Update : adding Wireframe sample
To solve your question regarding to adding the formula to the formula textbox when clicked. Here is some sample code. I use jQuery with a double click event.
HTML
<b>Formulas:</b><br/>
<i>Double click to append the formula.</i></br>
<select id="formulas" size="5">
<option>d_0</option>
<option>v_fix</option>
<option>f_Fc</option>
<option>a_sc</option>
</select>
<select id="operands" size="5">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<br/>
<span id="message" style="color: red"></span>
<hr/>
<b>Formula:</b><br/>
<textarea id="formula"></textarea>
JavaScript
$(document.ready( function() {
var formulas = $("#formulas");
var formula = $("#formula");
var operands = $("#operands");
var message = $("#message");
var expectFormula = true;
formulas.dblclick(function() {
if(expectFormula == true) {
var currentFormula = formula.val();
var appendFormula = formulas.val();
var newFormula = (currentFormula + " " + appendFormula).trim();
formula.val(newFormula);
expectFormula = false;
return;
}
message.html("Operand expected.");
});
operands.dblclick(function() {
if(expectFormula == false) {
var currentFormula = formula.val();
var appendFormula = operands.val();
var newFormula = (currentFormula + " " + appendFormula).trim();
formula.val(newFormula);
expectFormula = true;
return;
}
message.html("Formula expected.");
});
});
JSFiddle
https://jsfiddle.net/L1r3xdvq/1/
I am by no means a JavaScript expert, but this should demonstrate on how to do this.
Do note that you have to double check the user input on the server, even though it is created with JavaScript, it is possible to enter whatever you want and send this as formula.
I have a Html.TextBoxFor which I would like to assign some dynamic javascript to (the onchange event specifically):
#Html.TextBoxFor(model => answer.Value, new { #class = "answerinput", #onchange = "submitAnswer(\"" + Model.QuestionID.ToString() + "\")" });
However, when I examine the resulting HTML, the quotes around the value passed into the javascript function are encoded, which is a problem:
onchange="submitAnswer("3")"
I've tried a few things, like placing the string into an IHtmlString and then using the IHtmlString in the assignment but the results are always the same.
Is there a way to prevent MVC from encoding the value assigned to #onchange?
Thanks!
Alternatively, you should change the way you are attaching to the event:
Html.TextBoxFor(x => x.SomeProperty, new { rel = Model.QuestionID, #class = "SomeClass" });
Then in javascript, attach to the event:
$('.SomeClass').each(function()
{
$(this).change(function()
{
var questionId = $(this).attr('rel');
});
});
Try using single quotes, no escape character required.
#Html.TextBoxFor(model => answer.Value, new { #class = "answerinput", #onchange = "submitAnswer('" + Model.QuestionID.ToString() + "')" });
Is it possible when using Html.TextBoxFor to override the name attribute?
I have tried with no success. I need to use TextBoxFor to get client side validation to work, however for reasons I won't go into I need the name of the textbox to be different from the generated one.
I have tried the following:
#Html.TextBoxFor(x => x.Data, new { name = Model.Key + "_Data", id = Model.Key + "_Data" })
Which works for ID but not name. Is this possible?
Update: Looking into the code for TextBoxFor. It doesn't look like there is an easy way. Hopefully someone can prove me wrong.
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" })
Are you asking this because you want to apply a prefix to the name? If so, you can do this by setting ViewData.TemplateInfo.HtmlFieldPrefix in your Controller.
I learnt a lot about this stuff from Brad Wilson's blog.
EditorFor has an overload where you can supply the name attribute as a parameter:
#Html.EditorFor(expression, null, name)
Try EditorFor. you can pass string as template name if you want to make sure textbox is rendered even if property type is not string. If property is string already, it does not need templatename explicitly to render textbox, so you can pass null. Note that it does not require id parameter explicitly, it will infer it from element name. And all the validation things are still active with EditorFor
#Html.EditorFor(x => x.Data, "string", Model.Key + "_Data")
It is called Microsoft GOTCHA...
Use the name in caps, like this
#Html.TextBoxFor(m => m.Reply.Answer, new { Name = "Whatyouwant" })
ben's answer got me what I was looking for except you need to wrap in in Html.Raw
#Html.Raw(Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData"))
a little bit "unpretty"=), try:
#Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData")
For me, it works! I hope that help!
#Html.EditorFor(model => model.Nome, new { htmlAttributes = new { #class = "form-control", #maxlength = "80", #id = "NomeFilter", #Name = "NomeFilter" } })
#Html.EditorFor(Model => Model.Something, "name", "name", new {#class = "form-control" })
Not sure which of those two string parameters in the middle do the work, but it worked only when I typed both of them.
For this example, I was disabling form fields based on permissions, but still showing them. I had a hidden field to send the value to the controller, but wanted a different field name in the EditorFor.
First param after model value represents the "name" property, second is the new name.
#Html.EditorFor(m => m.UserName, "name", "UserNameDisabled", new { htmlAttributes = new { #class = "form-control", #disabled = "disabled"} });
Results in:
<input class="form-control text-box single-line" disabled="disabled" id="UserNameDisabled" name="UserNameDisabled" type="text" value="someEnteredValue" />
Keep it simple, your already providing the ID you should simply be able to use the method "TextBox" instead of "TextBoxFor" and it will work fine client side and server side. In addition, although the accepted answer will work but will produce duplicate Name attributes on your tag if you inspect it using a browser. The below solution does not have that problem.
MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)
#Html.TextBox(Model.Key + "_Data", Model.Key, new { id = Model.Key + "_Data" }
I am kind of stumped because, I want to format the value and add a html attribute for css class.
If I use #Html.TextBoxFor(m => m.DateModified)
- I can add html attribute but formatting does not work via DisplayFormat attribute on the member.
If I use #Html.EditorFor(m => m.DateModified)
- Formatting works but I cannot add html attribute
If I use #Html.TextBox("DateModified", Model.DateModified, ...)
- I get null reference exception when Model is null when the form is in add mode
What is the best way to achieve this?
I ended up solving this by creating a custom editor template for my date picker as so:
Shared/EditorTemplates/DateTime.cshtml
#model System.DateTime?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty, new { #class = "date-picker" })
Then in my original page continue to use
#Html.EditorFor(m => m.DateModified)
You could...
#Html.TextBoxFor(m => m.DateModified, new { Value = Model.DateModified.ToString("MM-dd-yyyy"), #class = "superCoolClassName"})
Use #Html.EditorFor(m => m.DateModified), because otherwise the DisplayFormat attribute will have no effect.
To add further attributes like a CSS class, you have to create an editor template for the DateTime.
Create a file EditorTemplates/DateTime.cshtml with the following content:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new
{
#class="date"
})
Please note that the value of the TextBox is not set with the Model directly, but rather with the TemplateInfo.FormattedModelValue, because that value will be formatted according to the DisplayFormat attribute while the Model not. (This took me quite some time to realize. :))
In simple cases this might be enough, e.g. if the CSS class can be the same for all date editors.
If you want to parametrize the attribute, you can do that as well, passing the attribute value parameter to the EditorFor.
#Html.EditorFor(m => m.DateModified, new { #class = "someClass" })
However, this parameter will be not automagically delegated to the HTML control as attribute, but you have to "handle it" in the template explicitly. According to my experiences you can access this parameter value in the ViewData in the template, so the parametrized template looks like this:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new
{
#class=ViewData["class"]
})
To prevent hardcoding the key/value pairs listed in EditorFor , convert the ViewData object to a Dictionary and pass that dictionary object to TextBox.
eg
#Html.EditorFor(m => m.DateModified, "Template", new { #class = "someClass", size=8 , htmlTag="custom" })
And in the template you have
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData.ToDictionary(c=>c.Key,c=>.Value))
To show json date in textbox (cshtml):
var d1 = ui.item.IssueDate;
var d = new Date(parseInt(d1.slice(6, -2)));
var Issdate = ("0" + (d.getMonth() + 1)).slice(-2) + '/' +
("0" + d.getDate()).slice(-2) + '/' +
d.getFullYear().toString();
$('#IssueDate').val(Issdate);