Editor showing data as plain text instead of HTML. It is saving correct formatted test all the way to DB - kendo-editor

I'm facing an issue where I can successfully save HTML text to DB using the Editor. Still, upon loading the exact text (with all the formatting tags), the Editor refuses to format it correctly and displays it as plain text:
#* Background *#
<div class="row mt-3">
<div class="col-12">
#Html.LabelFor(m => m.BackgroundConcessionaireContract, "Background of Concessionaire/Contract *", new { #class = "col-12 control-label" })
<kendo-editor for="BackgroundConcessionaireContract" style="height:350px" aria-label="editor"
placeholder="Background of Concessionaire/Contract">
<tools>...</tools>
</kendo-editor>
</div>
</div>
<hr class="cm-hr" />
#* Proposal Details *#
<div id="divProposalDetails" class="row mt-3">
<div class="col-12">
#Html.LabelFor(m => m.CommercialTermsDetails, "Commercial Terms Details *", new { #class = "col-12 control-label" })
<kendo-editor for="CommercialTermsDetails" style="height:350px" aria-label="editor"
placeholder="Commercial Terms Details">
<tools>...</tools>
</kendo-editor>
</div>
</div>
<hr class="cm-hr" />
#* Financial Analysis *#
<div class="row mt-3">
<div class="col-12">
#Html.LabelFor(m => m.FinancialAnalysis, "Financial Analysis *", new { #class = "col-12 control-label" })
<kendo-editor for="FinancialAnalysis" style="height: 350px" aria-label="editor"
placeholder="Financial Analysis">
<tools>...</tools>
</kendo-editor>
</div>
</div>
In the model, the fields are defined simply as:
public string BackgroundConcessionaireContract { get; set; }
public string CommercialTermsDetails { get; set; }
public string FinancialAnalysis { get; set; }
The output is like this:

I figured out that I had to set the Encoded parameter/attribute to false for this to work:
<kendo-editor for="CommercialTermsDetails" encoded="false" style="height:350px" aria-label="editor" placeholder="Commercial Terms Details">
</kendo-editor>

Related

Validation error working wit ASP.NET MVC .NET FRAMEWORK

your text
I added validation to my ASP.NET MVC .NET FRAMEOWRK project and get this error:
your text
Unable to cast object of type 'System.Int32' to type 'System.String'.
My project connect to data base with one table.
my code:
Customer.cs:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConnectToDB
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class Customers : IValidatableObject
{
[StringLength(1000, ErrorMessage = "Queue number must be no more than 1000 digits")]
[Required(ErrorMessage = "Queue number is required")]
[DataType(DataType.Text)]
[DisplayName("Queue number")]
public int queueNumber { get; set; }
[StringLength(30, ErrorMessage = "First name must be no more tha 1000 letters")]
[RegularExpression("^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")] // RegEx: Used to validate a person name
[Required(ErrorMessage = "First name is required")]
[DisplayName("First name")]
[DataType(DataType.Text)]
public string firstName { get; set; }
[StringLength(30, ErrorMessage = "Last name must be no more tha 1000 letters")]
[RegularExpression("^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")] // RegEx: Used to validate a person name
[Required(ErrorMessage = "Last name is required")]
[DisplayName("Last name")]
[DataType(DataType.Text)]
public string lastName { get; set; }
[Required(ErrorMessage = "Time customer enter is required")]
[DisplayName("Time customer enter")]
[DataType(DataType.Time)]
public Nullable<System.TimeSpan> timeCusEnter { get; set; }
// Validation for queue number using IValidatableObject interface:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
List<ValidationResult> errors = new List<ValidationResult>();
if (queueNumber < 0)
{
errors.Add(new ValidationResult("Queue number can not be negative.", new List<string> { "queueNumber" }));
}
return errors;
}
}
}
addCustomer.cshtml:
#model ConnectToDB.Customers
#{
ViewBag.Title = "addCustomer";
}
<link rel="stylesheet" href="~/CSS/addCusDesign.css" />
<link rel="stylesheet" href="~/CSS/Local.css" />
<body>
#*Menu:*#
<div class="navBar">
<span class="navItem">
#Html.ActionLink("Dequeue to the queue", "addCustomer")
</span>
<span class="navItem">
#Html.ActionLink("Customers list", "customersList")
</span>
</div>
<h2>Enqueue</h2>
<span id="secondTitle">Fill in the following details, then press the button and enter the queue.<br>Have a good day :)</span>
<br />
<br />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Customers</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.queueNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.queueNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.queueNumber)
</div>
</div>
<br />
<div class="form-group">
#Html.LabelFor(model => model.firstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.firstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.firstName)
</div>
</div>
<br />
<div class="form-group">
#Html.LabelFor(model => model.lastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.lastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.lastName)
</div>
</div>
<br />
<div class="form-group">
#Html.LabelFor(model => model.timeCusEnter, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.timeCusEnter, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.timeCusEnter)
</div>
</div>
<br />
<br />
#Html.ValidationSummary(true, "Add customer was unsuccessful. Please coorect the following errors: ")
#*Dequeue customer to the queue input: *#
<div class="form-group">
<div class="GetInTheQueue">
<input type="submit" value="GET IN THE QUEUE" class="btn btn-default" />
</div>
</div>
</div>
}
<br />
<br />
#*Carusel in boostrap: *#
<!-- #region Carusel -->
<div id="carouselExampleFade" class="carousel slide carousel-fade" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="~/Images/image1.jpeg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="~/Images/image2.png" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="~/Images/Image3.jpeg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="~/Images/Image4.jpeg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="~/Images/Image5.jpeg" class="d-block w-100" alt="...">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleFade" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<!-- #endregion -->
<br />
<br />
#*Images: *#
<!-- #region Images -->
<div class="images">
<img width="200" height="200" src="~/Images/image1.jpeg" alt="Queue image1" />
<img width="200" height="200" src="~/Images/image2.png" alt="Queue image2" />
<img width="200" height="200" src="~/Images/Image3.jpeg" alt="Queue image3" />
<img width="200" height="200" src="~/Images/Image4.jpeg" alt="Queue image4" />
<img width="200" height="200" src="~/Images/Image5.jpeg" alt="Queue image5" />
</div>
<!-- #endregion -->
</body>
Would appreciate help
The validation work for me yesterday, but today not working.

Input field keeps switching between text and date in ASP.NET Core MVC application

I'm having a problem with an input field switching between type=text (when it's not focused) and type=date (when it's focused). I'm using .NET Core 3.1 framework.
Model:
public class DocumentVersionModel
{
public int Id { get; set; }
public int DocumentModelId { get; set; }
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreationDate { get; set; }
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime LastChangeDate { get; set; }
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime DocumentDate { get; set; }
public string Content { get; set; }
public int Version { get; set; }
public DocumentModel Document { get; set; }
}
The format yyyy-MM-dd is needed for the database and is the one displayed when the input field isn't focused. The format I need to display the dates is mm/dd/yyyy, but I can't change the DateFormatString (and removing ApplyFormatInEditMode = true didn't work).
This is the form in the RazorPage:
<form asp-action="Edit">
<br />
<div class="row justify-content-center">
<div class="col-12 form-group">
<label>Titolo</label>
<input asp-for="Title" class="form-control" />
</div>
<div class="col">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" id="iddoc" />
<div class="form-group">
<label>Data Documento</label>
<input asp-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).DocumentDate" class="form-control" />
<span asp-validation-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).DocumentDate" class="text-danger"></span>
</div>
<div class="form-group">
<label>Data Creazione</label>
<input asp-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).CreationDate" class="form-control" readonly="readonly" />
</div>
<div class="form-group">
<label>Data Ultima Modifica</label>
<input asp-for="DocumentVersion.FirstOrDefault(q => q.Version==Model.ActiveVersion).LastChangeDate" class="form-control" readonly="readonly" />
</div>
</div>
</form>
A little note about the form: if I use type="date" or "datetime" inside the input tag, the type keeps changing between text and date, but if I use "datetime-local" is shown correctly (but it displays the time too which I don't need).
This is the GIF of what happens:
https://imgur.com/YXKVAMO
This is the very bad and inefficient jQuery solution I used to "fix" the problem:
$('#DocumentDate, #LastChangeDate, #CreationDate').attr('type','date'); //when the page loads
$(document).click(function () {
if ($('#DocumentDate').not(':focus') || $('#LastChangeDate').not(':focus') || $('#CreationDate').not(':focus'))
$('#DocumentDate, #LastChangeDate, #CreationDate').attr('type','date');
});
So what is your current problem? Do you not want to use jquery to
achieve it?
I think the method you are using by jquery is implemented very well because you cannot change the date type input control to display the date format you want: link.
Another solution is to use Datepicker plugin for jquery UI, but this cannot avoid using jquery.
Here is the example based jquery UI Datepicker :
#model WebApplication_core_mvc.Models.DocumentVersionModel
#{
ViewData["Title"] = "DateEdit";
}
<h1>DateEdit</h1>
#section Scripts{
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker();
$('.datepicker').datepicker("option", "dateFormat", "mm/dd/yy"); //Initialise any date pickers
});
</script>
}
<form asp-action="Edit">
<br />
<div class="row justify-content-center">
<div class="col-12 form-group">
<label>Titolo</label>
<input asp-for="DocumentModelId" class="form-control" />
</div>
<div class="col">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" id="iddoc" />
<div class="form-group">
<label>Data Documento</label>
#Html.TextBoxFor(model => model.CreationDate, new { #class = "form-control datepicker" })
<span asp-validation-for="CreationDate" class="text-danger"></span>
</div>
<div class="form-group">
<label>Data Creazione</label>
#Html.TextBoxFor(model => model.LastChangeDate, new { #class = "form-control datepicker" })
</div>
<div class="form-group">
<label>Data Ultima Modifica</label>
#Html.TextBoxFor(model => model.DocumentDate, new { #class = "form-control datepicker" })
</div>
</div>
</div>
</form>
Here is the result:

MVC 5 HTML helper for client side validation for value not in model

I'm following the MVC tutorial here to add a search/filter textbox:
http://www.asp.net/mvc/overview/getting-started/introduction/adding-search
I've added the filter textbox to my page:
#using (Html.BeginForm()) {
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
How do I perform client side validation on the textbox to ensure something was entered?
When you automatically created the controller and views based on a model, it creates this handy HTML helper:
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
Can something similar be used for a value not in your model or do you have to add custom jquery/html?
Edit:
Thanks for the direction everyone. Just adding some more information now. I've created a new class in my existing model:
public class SearchItem
{
[Required]
[StringLength(100, MinimumLength = 5, ErrorMessage = "This is my test error message")]
public string SearchString { get; set; }
}
Then inside the controller, I've created a partial view:
[ChildActionOnly]
[AllowAnonymous]
public PartialViewResult Search()
{
return PartialView();
}
Then I've created a new Search.cshtml with:
#model App.Models.SearchItem
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<h4>#Html.LabelFor(model => model.SearchString, "Search:", htmlAttributes: new { #class = "control-label col-md-2" })</h4>
<div class="col-md-10 input-max-width">
#Html.EditorFor(model => model.SearchString, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SearchString, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-primary" />
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Then on my existing page, I add it with this:
#Html.Action("Search", "Items")
When I enter no text into the textbox and click the Search button, the page just refreshes and I get no client side validation.
My HTML looks like this:
<form action="/Items/Index" method="post"> <div class="form-group">
<h4><label class="control-label col-md-2" for="SearchString">Search:</label></h4>
<div class="col-md-10 input-max-width">
<input class="form-control text-box single-line" data-val="true" data-val-length="This is my test error message" data-val-length-max="100" data-val-length-min="5" data-val-required="The SearchString field is required." id="SearchString" name="SearchString" type="text" value="" />
<span class="field-validation-valid text-danger" data-valmsg-for="SearchString" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Search" class="btn btn-primary" />
</div>

MetadataType attribute is not working for details view in MVC3

I am newbie in entity framework and I have created Ado.Net Entity Data model which contains two properties FullName and EmailAddress. what I am trying to do is that in my details view I want to display Full Name instead of FullName. To accomplish this I have written code like this:
namespace ScaffFolding.Models
{
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
}
public class EmployeeMetaData
{
[Display(Name="Full Name")]
public string FullName { get; set; }
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
}
}
My edmx file also sharing the same namespace and have same class named as Employee
Now the problem is that in Details view this code is not working means showing FullName instead of Full Name but in Create view it's working as expected.
Here is code for my Detail view:
#model ScaffFolding.Models.Employee
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>Employee</legend>
<div class="display-label">FullName</div>
<div class="display-field">
#Html.DisplayFor(model => model.FullName)
</div>
<div class="display-label">Gender</div>
<div class="display-field">
#Html.DisplayFor(model => model.Gender)
</div>
<div class="display-label">Age</div>
<div class="display-field">
#Html.DisplayFor(model => model.Age)
</div>
<div class="display-label">HireDate</div>
<div class="display-field">
#Html.DisplayFor(model => model.HireDate)
</div>
<div class="display-label">EmailAddress</div>
<div class="display-field">
#Html.DisplayFor(model => model.EmailAddress)
</div>
<div class="display-label">Salary</div>
<div class="display-field">
#Html.DisplayFor(model => model.Salary)
</div>
<div class="display-label">PersonalWebSite</div>
<div class="display-field">
#Html.DisplayFor(model => model.PersonalWebSite)
</div>
</fieldset>
<p>
#Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
#Html.ActionLink("Back to List", "Index")
</p>
Can anyone please tell me what is going wrong here?
DisplayFor is used for picking up templates from DisplayTemplates folder.
more at What is the #Html.DisplayFor syntax for?
Where as, LabelFor picks stuffs from data annotations
Ok I got the answer what is going wrong here. The problem is in the code generated by VS:
Visual Studio is generating the Details view using div tag as shown below
<div class="display-label">FullName</div>
Where as LabelFor is being used by Vistual Studio for Create view:
#Html.LabelFor(model => model.FullName)

Validate Modal Form

I am trying to popup a form so user fill it then I save that record. If data is wrong I want to inform the user just a classic validation issue.
I am trying this code but when model is not valid it show the mistake but literally it only returns what is in the partial view, it is not loading my layout nor my modal form, all I get is a white page just with my partial.
so what am I doing wrong?
This is my modal form:
And after validation all I get is this:
Code:
Model:
public class Car
{
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 6)]
public string Model { get; set; }
public string Brand { get; set; }
public string Year { get; set; }
public string Color { get; set; }
}
View:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Car</h4>
</div>
<div class="modal-body">
#Html.Partial("CreatePartialView",new Car())
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="savechanges">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
my partial:
#model ControliBootstrap.Models.Car
#using (Ajax.BeginForm("ModalAdd", "Cars",new AjaxOptions()
{
UpdateTargetId = "mymodalform"
}))
{
<div class="form-horizontal" id="mymodalform">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Model, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Model)
#Html.ValidationMessageFor(model => model.Model)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Brand, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Brand)
#Html.ValidationMessageFor(model => model.Brand)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Year, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Year)
#Html.ValidationMessageFor(model => model.Year)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Color, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Color)
#Html.ValidationMessageFor(model => model.Color)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
and finlly my controler:
public ActionResult ModalAdd(Car car)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView("CreatePartialView",car);
}
Don't forget to include jQuery Unobtrusive AJAX - it's the library that makes normal HTML forms have some AJAX capabilities.

Resources