How Bind Razor Html Retrieved From Database to DevExpress HtmlEditor? - ajax

I am working on a asp.net mvc project where I am using DevExpress HtmlEditor. I have a html template stored in database. In this template I have used Razor syntext like #foreach(...). I am retrieving this html template by an action method called GetHtmlTemplate() and I am calling the action method using ajax and trying to set the html template as Value of dev express html editor. But unfortunately devexpress htmleditor could not recognize the razor syntaxes and it out put like #foreach(...) as it is. But if I set the html as Value of htmleditor rather retrieving from database it workes fine. don't know what is the difference.
bellow codes are for easy reference...
DevExpress HtmlEditor
`
#(Html.DevExtreme().HtmlEditor()
.ID("myHtmlEditor")
.Height(800)
.OnValueChanged("onChangeValue")
.Toolbar(toolbar => toolbar.Items(
items =>
{
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.Bold);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.Color);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.AlignLeft);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.AlignCenter);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.AlignRight);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.InsertTable);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.InsertRowAbove);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.InsertRowBelow);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.InsertColumnLeft);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.InsertColumnRight);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.DeleteColumn);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.DeleteRow);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.DeleteTable);
items.Add().Name(DevExtreme.AspNet.Mvc.HtmlEditorToolbarItem.Separator);
})
)
)
`
ajax function
`
function getHtmlTemplate() {
$.ajax({
url: "#Url.Action("GetHtmlTemplate", "Admin")",
type: "GET",
data: {},
contentType: "application/json",
dataType: "json",
success: function (res) {
var editorInstance = $("#myHtmlEditor").dxHtmlEditor("instance");
editorInstance.option("value", res.HtmlTemplate);
},
error: function (error) {
alert(error.Message);
}
});
}
`
Action Method
`
public JsonResult GetHtmlTemplate()
{
var htmlTemplate = db.MyTable.Select(item => new { HtmlTemplate = item.HtmlTemplate}).FirstOrDefault();
return Json(htmlTemplate, JsonRequestBehavior.AllowGet);
}
`
I am trying for a long to solve it but coludn't find a way. Please help...

Related

ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data

I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}

jQuery Ajax returns undefined result from asp.net core controller's POST action

Can't make friends out of my AJAX and MVC 6 controller.
This is how I define AJAX call for SetFormValues POST-action:
Index.cshtml
$.ajax({
type: "Post",
url: "Home/SetFormValues",
data: { Name: name, Phone: phone },
dataType: "json",
success: function (result) {
SuccessFunction(result)
},
error: function () {
alert("ALARM!");
},
async: false
})
I see that the controller works and executes SetFormValues action which is defined as the following:
HomeController.cs
[HttpPost]
public JsonResult SetFormValues(string Name, string Phone)
{
string NameErrorStr = string.IsNullOrWhiteSpace(Name) ? "Обязательное поле" : string.Empty;
string PhoneErrorStr = string.IsNullOrWhiteSpace(Phone) ? "Обязательное поле" : string.Empty;
var result = new { NameError = NameErrorStr, PhoneError = PhoneErrorStr };
var jresult = Json(result);
return jresult;
}
Debugger shows that action executes and my resulting JSON object fills correctly:
Finally, his is how SuccessFunction(result) is defined:
Index.cshtml again
function SuccessFunction(result) {
alert("Success function shit executed. result=" +
result + "NameError=" +
result.NameError + ". PhoneError=" +
result.PhoneError);
$("#nameerror").append(result.NameError);
$("#phoneerror").append(result.PhoneError);
}
Function works, alert is raised but result stay 'undefined' no matter what I do:
result = [object Object]
result.val = undefined
Maybe I have to deserialize JSON result properly or fill some properties in it's declaration above, I don't know.
I'm using the lattest libraries for jquery, validate and unobtrusive.
I also tried JSON.parse(result), as it mentioned in the lattest jQuery specification, but it didn't work as well.
Please, help me :)
In asp.net core, by default, the serializer uses camelCase property names for json serialization. So your result will be like this
{"nameError":"some message","phoneError":"some message here"}
Javascript is case sensitive. So use the correct case
$("#nameerror").append(result.nameError);
$("#phoneerror").append(result.phoneError);
For reference : MVC now serializes JSON with camel case names by default
its working perfectly when i have added this line in startup file
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddDbContext<DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DbCrudOperation")));
}
function Edit(id) {
$.ajax({
type: 'GET',
url: "/AjacCrud/EditPahe/" + id,
dataType: 'JSON',
contentType: "application/json",
success: function (response) {
$("#nameEmp").val(response.ID);
console.log(response.ID);
},
error: function (GetError) {
alert(GetError.responseText);
}
});
};

Ajax not returning desired results or not working at all

I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

call controller using ajax failing to find controller

I am trying to call a controller via ajax without to much luck.
I have create this in my view
<input type="submit" id="preview-email" value="Preview Email" />
<script type="text/javascript">
$("#preview-email").click(function () {
var p = { "email": "1223" };
$.ajax({
url: '/BusinessController/PreviewEmail',
type: "POST",
data: p,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
});
</script>
My controller
[HttpPost]
public ActionResult PreviewEmail(string email)
{
// string d = ViewData["editor"].ToString();
string e = System.Web.HttpUtility.HtmlDecode(email);
EmailModel model = new EmailModel() { EmailBody = e };
return PartialView("_PreviewEmail", model);
}
Turning on fiddler is telling me that its a 500 error. What have I done wrong? I've placed a breakpoint on my controller however it doesnt get that far
Your URL should be:
'/Business/PreviewEmail'
instead of:
'/BusinessController/PreviewEmail'
However, the recommended practice for building URLs is to use your routes:
Url.Action("PreviewEmail", "Business")
BTW, you have another problem in your code. By setting "application/json" as your contentType, MVC will expect a JSON string. However, when you assign a JavaScript object to the data property of $.ajax(), jQuery will serialize the value to this:
email=1223
So you'll want to assign a string to the data property instead by doing this:
var p = '{ "email": "1223" }';
#Url.Action doesn't work inside the JS file. What if my call to Controller/Action is inside JS file?
For now I'm, retrieving the location.href and then replacing the Action name.
(This may not be a wise thing to do)

Resources