CKEditor text value is lost on post in BLAZOR - ckeditor

I have a Textarea control in a Blazor applicaiton that is a CKEditor 5 WYSIWYG editor.
<div class="form-group">
<label for="image">Content</label>
<textarea id="editor" class="form-control" #bind="#PostObject.Content" />
<ValidationMessage For="#(() => PostObject.Content)" />
</div>
When the form gets submitted the value of PostObject.Content is always null. If I remove the CKEditor element the posted value is correct.
The CKEditor is initialised by calling a Javascript function called RTF on a button click (launches the form in a modal popup) -
await jsRuntime.InvokeAsync<string>("RTF", "editor");
The function is located in index.html
function RTF(editorId) {
ClassicEditor.create(document.querySelector('#' + editorId));
}

For me works with the function CKEDITOR.editor.getData.
https://ckeditor.com/docs/ckeditor4/latest/guide/dev_savedata.html
Your code can be changed to below
<EditForm Model="#postObject" OnValidSubmit="SaveObject">
<div class="form-group">
<DataAnnotationsValidator />
<ValidationSummary />
<InputTextArea id="editor" #bind-Value="#PostObject.Content" Class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Save</button>
</EditForm>
#code {
PostObject postObject= new PostObject();
string contentFromEditor = string.Empty;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
await jsRuntime.InvokeAsync<string>("RTF", "editor");
await base.OnAfterRenderAsync(firstRender);
}
private async Task SaveObject()
{
contentFromEditor = await JSRuntime.InvokeAsync<string>("CKEDITOR.instances.editor.getData");
}
}

Related

How to implement reCaptcha "v2" in ASP.NET Core MVC?

I want to add Recaptcha, the second version, not another version, and I want it to be in ASP.NET Core, not MVC, and I searched a lot and did not find the solution.. I hope for help
I have a login controller :
public IActionResult Login([Bind("Username , Password")] User userLogin)
{
const string id = "id";
var auth = _context.Users.Where(x => x.Username == userLogin.Username &&
x.Password == userLogin.Password).SingleOrDefault();
var x = _context.Users.Where(x => x.Username == userLogin.Username && x.Password
== userLogin.Password).Select(i => i.UserId).FirstOrDefault();
if (auth != null)
{
// 1 > admin
// 2 > Accountant
// 3 > customer
switch (auth.RoleId)
{
case 1: // admin
HttpContext.Session.SetInt32(id, (int)x);
return RedirectToAction("Index", "Home");
case 2:
HttpContext.Session.SetInt32(id, (int)x);
return RedirectToAction("AccountantDashboard", "Home");
case 3:
HttpContext.Session.SetInt32(id, (int)x);
return RedirectToAction("Home", "Home");
}
}
return View();
}
and another for view (head and body)
<form asp-action="Login" enctype="multipart/form-data">
<div class="input-group">
<label asp-for="Username" class="input--style-2" placeholder="username"></label>
<input asp-for="Username" class="input--style-2" />
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<div class="input-group">
<label asp-for="Password" class="input--style-2" placeholder="Password"></label>
<input asp-for="Password" type="password" class="input--style-2" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="p-t-30">
<button class="btn btn--radius btn--green" type="submit" value="Create">Login</button>
</div>
<div style="position: relative ; left: 350px ; bottom: -50px">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Home">Or back to home page</a>
</div>
</form>
As far as I know, the reCaptcha "v2" is build based on js and we could directly use it inside the html page.
We could use it like this, firstly put below codes inside your view and it is used to put the g-recaptcha and it contains a callback method, if this method is called that means the user has passed the validation and you could show the button by using JQuery or javascript.
<div class="g-recaptcha" data-callback="recaptcha_callback" data-sitekey="xxxxx"></div>
Like this:
<script type="text/javascript">
function recaptcha_callback(){
$('#login).show();
}
</script>
More details, you could refer to this article.

Why has my unobtrusive ajax stopped updating my partial view in ASP.NET Core 3.1?

I'm using unobtrusive ajax inside a kendo window to update a form once it's been filled in. The form should update the Id's of the DOM elements dynamically and also show the relative data inside the form as returned from the controller.
Let's start, here is the window element that houses the partial view which is a form:
#model Requirement
#{
int localId = Model.Id;
}
<div class="window-content">
<form method="post" data-ajax-url="/Home/Process_Requirement" data-ajax="true" data-ajax-method="post" data-ajax-loading="#spinner" data-ajax-update="#update-form-requirement" data-ajax-success="form_requirement_success">
<div id="update-form-requirement">
<partial name="_Form_Requirement" />
</div><!--/update-panel-->
<div class="window-footer">
<div class="container">
<div class="row no-gutters">
<div class="col">
<button type="submit" class="input-submit float-right">Save</button>
</div>
</div>
</div>
</div>
</form>
</div>
_Form_Requirement
#model Requirement
#{
int localId = Model.Id;
}
<div class="tab-content">
<div class="tab-pane fade show active" id="form-requirement-basic-#localId" role="tabpanel" aria-labelledby="requirement-tab">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="text" id="Id_#localId" name="Id" asp-for="Id" readonly />
<input type="text" id="CreatedUser_#localId" asp-for="CreatedUser" readonly />
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label>Vessel Type</label>
<kendo-dropdownlist name="VesselType"
for="VesselType"
id="VesselType_#localId"
datatextfield="TypeName"
datavaluefield="Id"
min-length="3"
style="width: 100%"
value-primitive="true"
option-label="Select vessel type"
footer-template="<button class='dropdown-button k-icon k-i-plus-outline' data-object-title='Add vessel type' data-object-function='_Window_Vessel_Type' onclick='open_data_window(this, event)'></button>"
filter="FilterType.Contains">
<datasource type="DataSourceTagHelperType.Ajax" page-size="80">
<transport>
<read url="/Vessel/ReadVesselTypes" />
</transport>
</datasource>
<popup-animation>
<open duration="300" effects="fadeIn" />
<close duration="300" effects="fadeOut" />
</popup-animation>
</kendo-dropdownlist>
</div>
</div>
</div>
</div>
</div>
</div>
When the form is submitted the controller action does the following:
/Home/Process_Requirement
public IActionResult Process_Requirement(Requirement model)
{
//Define the partial view we want
string modal = "_Form_Requirement";
//If the Id is 0 then create a new requirement
if (model.Id == 0)
{
if (ModelState.IsValid)
{
try {
_requirementService.InsertRequirement(model);
var getData = _requirementService.GetRequirement(model.Id);
return PartialView(modal, getData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
else
{
try
{
_requirementService.UpdateRequirement(model);
return PartialView(modal, model);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return PartialView(modal);
}
So, when you first open a window to create a new requirement the localId is 0 because you're not editing one, that's expected behavior.
When you then fill in all the details and submit the form, the data is posted to the database and saved correctly but the model doesn't seem to update with the new data, for example the input for the Id remains as 0:
<input type="text" id="Id_#localId" name="Id" asp-for="Id" readonly />
yet the id for the input updates to the newly created id number. Why is this happening and can I do anything about it?
you have a bug. fix the last return
return PartialView(modal,model);
Is the Id primary key? If so, it is not recommend to change the primary key, you should add a new column to be the key.
the data is posted to the database and saved correctly but the model doesn't seem to update with the new data
This could be caused by the concurrency issues. I can't see your update code now, but you can
try to change your update code like this:
public async Task<IActionResult> Process_Requirement(Requirement model)
{
string modal = "_Form_Requirement";
if (model.Id == 0)
{
//....
}
else //to update
{
await TryUpdateModelAsync<Requirement>(_context.Requirements.FirstOrDefault(x => x.RId ==model.RId),"",c => c.Id, c => c.CreatedUser);
_context.SaveChanges();
return PartialView(modal, model);
}
return PartialView(modal);
}
My Model:
public class Requirement
{
[Key]
public int RId { get; set; } //new column
public int Id { get; set; }
public string CreatedUser { get; set; }
}
And in partial, pass the key with a hidden field:
<input type="text" asp-for="RId" hidden/>
<input type="text" id="Id_#localId" name="Id" asp-for="Id" />
<input type="text" id="CreatedUser_#localId" asp-for="CreatedUser" />
Result:

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

Hot Towel Angular data-ng-show not working during validation

Hello anyone has anyone tried doing a validation using angularjs in a with Hot Towel template?
Basically i have a property in my angular controller which is binded(two way) in my view.
I just want to do a simple required validation, and then show a <span> element with the message.
here is my controller code
(function () {
'use strict';
var controllerId = 'login';
angular.module('app').controller(controllerId, ['$scope', 'common', 'userservice','$location', login]);
function login($scope, common, userservice, $location) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
vm.title = 'Login';
//view model for credentials
vm.email = null;
activate();
function activate() {
common.activateController([], controllerId)
.then(function () { log('Activated Login View'); });
}
}
})();
and this is my view
<div data-ng-controller="login as vm">
<form name="loginform" id="loginform" novalidate data-ng-submit="loginuser()">
<fieldset>
<legend>Login</legend>
<p>
<label>Email</label>
<input type="email" data-ng-model="email" placeholder="Email" required />
<span data-ng-show="loginform.email.$error.required">*</span>
</p>
</fieldset>
</form>
</div>
i dont know what the problem is, but the <span> just wont show. am i missing something?
You have to set 'name' attribute to your input email :
<input type="email" name="email" data-ng-model="email" placeholder="Email" required />
For each field of your form, angularjs will set a value like: loginform[name-attribute].
For your information, your span will be visible only when required error is triggered (when your email is not empty, your span will be hidden).
[EDIT] See this fiddle: http://jsfiddle.net/k82at

how to validate a form without displaying any error messages

I do not understand how I can validate a form with jquery validate to display the Submit button or not.
My javascript is as follows:
ko.bindingHandlers.jqValidate = {
init: function (element, valueAccessor, option) {
var element = element;
var validateOptions = {
ignore: [":hidden:not(required)"],
focusCleanup: true,
onsubmit: true
};
function displaySubmitButton() { // Remove/Add class to submit button
if ($('form').valid()) $('.toSave').show();
else $('.toSave').hide();
}
$('form').bind('onchange keyup onpaste', function (event, element) {
if ($('form').valid() === true && $(element).not('.resetForm')) $('.toSave').show();
else if ($(element).not('.resetForm')) $('.toSave').hide();
});
}
};
My form :
<ol class="MutColor13 mouseOver" data-bind="jqValidate: {}">
<li class="rightCol">
<strong>
<label for="iEmailReply"><asp:Literal runat="server" ID="lEmailReply" /></label>
</strong>
<input id="iEmailReply" name="EmailReply" type="text" tabindex="2"
class="MutColor13 email"
data-bind="value: communication.Message.ReplyEmail, valueUpdate: 'afterkeydown'"
required="required" />
</li>
<li class="leftCol">
<strong>
<label for="iEmailFrom"><asp:Literal runat="server" ID="lEmailFrom" /></label>
</strong>
<input id="iEmailFrom" name="EmailFrom" type="text" tabindex="1"
class="MutColor13 email"
data-bind="value: communication.Message.SenderEmail, valueUpdate: 'afterkeydown'"
required="required" />
</li>
<!-- and more form input -->
</ol>
My submit button :
<div class="buttonBlock rightButton" data-bind="fadeVisible: validateMessage()">
<a class="MutButton3 toSave" data-bind="click: saveMessage"><span class="MutButton3">submit</span></a>
</div>
when I type "$ ('form'). valid ()" in the firebug console, all error messages appear. I do not think the submit button is the problem because I have not clicked at this point
How do I enable the display of the error message from the input short change while allowing the display of the submit button if fields (and any other form fields in the page) if all fields are valid?
I was inspired by this question: jquery validate: IF form valid then show submit button
a working demo : http://jquery.bassistance.de/validate/demo/
but the button is displayed continuously
ok I think this could work:
http://jsfiddle.net/Ay972/10/
what I did :
$('form').bind('change oninput', function (event, element) {
console.log('formLive :: ', $(event));
if ($('form').valid() === true && $(element).not('.resetForm')) $('.toSave').show();
else if ($(element).not('.resetForm')) $('.toSave').hide();
});
the 'change oninput' seems to work.

Resources