MVC4, TinyMCE.MVC, can't set tinymce control content after Ajax call - ajax

MVC4, downloaded TinyMCE.MVC : content of tinymce control need to be retrieved by Ajax call and set into that tinymce control. So far my attempts to set html content in tinymce control have failed. I have to use Ajax call. Is there way to do that?
Thank you.
VIEW:
<div id="divTinyMCE">
#Html.EditorFor(model => model.myContent)
</div>
<button type="button" id="btnGetContent" onclick="getContent()">Get Content</button>
#section scripts{
<script type="text/javascript">
function getContent() {
var parm1 = 1;
var parm2 = 2;
$.ajax({
type: "POST",
url: '/Home/GetContent',
data: { parm1: parm1, parm2: parm2},
success: function (data) {
alert("data from ajax = " + data.toString()); // data is html
//tinymce.set(data.toString()); // does not set anything
//tinymce.html(data); // does not set anything
$("#tinymce").html(data); // does not set anything
}
}); // AJAX call
}
</script>
}
CONTROLLER :
public ContentResult GetContent(int parm1, int parm2)
{
string contentFound = findContent(parm1); // contentFound is HTML string
return Content(contentFound);
}

I finally figured it out:
tinyMCE.activeEditor.setContent(data);

Related

MVC Core ajax and return result is a view

MVC Core, NET 5, not razor pages.
On a view I have three select components (bootstrap-select). I populate them via ViewModel.
"Get request -> Controller -> return View(viewModel);"
What I want...
When I changed value in any select component I do a post request (ajax) to the same controller (other method) and return view with repopulated data.
"'Post request -> Controller -> return View(changedModel);"
As I understood when I did ajax request I should handle it result in success and other cases.
What I should to do to reload page with new data?
Is it possible to achive this with this approach?
Yes, this is possible and you do not need to reload the page, just append the returned html to wherever you want it.
$.ajax({
type: "POST",
url: {your_url},
dataType: "html",
success: function (html) {
$("#someDiv").html(html);
}
});
What I should to do to reload page with new data?
If the post action return the same view as the get action and you want to reload the whole page, I think there is no need to use ajax. You can just redirect to post action with a form submission. If the view returned by the post action is a partialview you want render to the current view, you can use it like that in #cwalvoort answer.
Based on advices of cwalvoort and mj1313
I did:
Render main page with partials. ViewModel transfered to a partial as a parameter
On main page I added eventListners to controls with JS.
When control changes - ajax request to backend happens Controller/GetPartialView
Result from ajax replace html in partial section
Programmatically show needed components, re-add eventListners
PS Really need to learn Blazor or UI Framework :)
Code samples:
// JS
document.addEventListener("DOMContentLoaded", function (event) {
BindSelectActions();
});
function BindSelectActions() {
$('#selectGroups').on('hidden.bs.select', DoPartialUpdate);
$('#selectCompanies').on('hidden.bs.select', DoPartialUpdate);
$('#selectPeriods').on('hidden.bs.select', DoPartialUpdate);
}
function DoPartialUpdate(e, clickedIndex, isSelected, previousValue) {
// ToDo: Implement common script with "CallBackend" function
$.ajax({
type: "POST",
url: 'https://localhost:44352/TestController/TestGetPartial',
// no data its a stub at the moment
// data: $('#form').serialize(),
success: function (data, textStatus) {
$("#testControls").html(data);
$('#selectGroups').selectpicker('show');
$('#selectCompanies').selectpicker('show');
$('#selectPeriods').selectpicker('show');
BindSelectActions();
}
});
}
// Controllers
[HttpGet]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public async Task<IActionResult> Main()
{
// ViewModel = _helper -> _mediator -> query -> context
return await Task.Run(() => View(new TestViewModel()));
}
[HttpPost]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public IActionResult TestGetPartial(TestViewModel model)
{
// ViewModel = _helper -> _mediator -> query -> context
var result = new TestViewModel();
result.IsPageReload = "yes";
result.TestCollection = new string[] { "A", "B", "C" };
result.Companies = new List<SelectListItem> { new SelectListItem { Value = "999",
Text = "Test" } };
// ModelState.Clear();
return PartialView("_TestPartial", result);
}
// Main and partial views
#model TestViewModel
#{
ViewData["Title"] = "Test";
}
<div id="testControls">
#await Html.PartialAsync("_TestPartial", Model)
</div>
#section Scripts {
<script type="text/javascript" src="~/js/test.js" asp-append-version="true">
</script>
}
#model TestViewModel
<form>
<div class="d-flex flex-row justify-content-between mt-4">
<div><select id="selectGroups" asp-for="Groups" asp-items="Model.Groups"
class="selectpicker" data-live-search="true" data-style="btn-outline-dark"
title="Group"></select></div>
<div><select id="selectCompanies" asp-for="Companies" asp-items="Model.Companies"
class="selectpicker" data-live-search="true" data-style="btn-outline-dark"
title="Company"></select></div>
<div><select id="selectPeriods" asp-for="Periods" asp-items="Model.Periods"
class="selectpicker" data-live-search="true" data-style="btn-outline-dark"
title="Period"></select></div>
<div><button type="button" class="btn btn-outline-dark">Import</button></div>
</div>
</form>
<div>
#{
if (null != Model.TestCollection)
{
foreach (var item in Model.TestCollection)
{
<p>#item</p>
<br>
}
}
}
</div>

CORE 2 MVC Ajax redirect to display a view

I have an application that uses the jQuery Datatable and I want to click on a row, pick up the id, and then bring up a view that allows for editing of that view and updating the underlying database.
Ajax gets me to the controller-action that for the edit view but I can't get the view itself to display. Instead, the controller action just returns to ajax. I've tried numerous tactics with no joy. Here is a simple example based upon a standard CORE template:
#section scripts{
<script>
$(document).on('click', 'button.number', function () {
alert($(this).val());
$.ajax({
method: 'GET',
url: '#Url.Action("About", "Home")'
});
});
</script>
}
<h3>Home Page</h3>
<div>
<button href="#" type="button" class="number" id="one" value="1">1</button>
<button href="#" type="button" class="number" id="two" value="2">2</button>
</div>
Running the debugger shows that About action is called OK but the view isn't rendered - it just returns to ajax. I've tried all sorts of redirection but any "return" just goes back to ajax.
Is there away around this or perhaps a better way to get from the JS to the controller-action? Thanks
EDIT:
Batuhan gets the credit for his solution but I'm re-posting it to clean up a little syntax and add the parameter passing that was my initial goal.
$(document).on('click', 'button.number', function () {
var id = $(this).val();
alert(id);
$.ajax
({
method: 'GET',
url: '#Url.Action("About", "Home")',
}).success(function (result) {
window.location.href = '/home/about/' + id;
});
});
And here is Home Controller for the About Action:
public IActionResult About(int id)
{
string parm2 = id.ToString();
ViewBag.msg = parm2;
return View();
}
And the About page:
#{
ViewData["Title"] = "About";
}
<p>
<h1> #ViewBag.msg </h1>
</p>
All works as initially hoped for!
$(document).on('click', 'button.number', function () {
alert($(this).val());
$.ajax({
method: 'GET',
url: '#Url.Action("About", "Home")'
}).success: function(result){
///this line
window.href='redirect url';
}});;
});
this is a solution cause you cant redirect from ajax call. it returns The view in html form So if you want to postback you needto use window.href="url";

on check box check send value to partial view and update it mvc 3

i have two partial view one is having a 5 checkbox (for filtering) and another will display the filtered data.
<input type="checkbox" data-toggle="checkbox" id="2000-5000"/>Rs.2000-Rs.5000
<input type="checkbox" data-toggle="checkbox" id="2000-5000"/>Rs.2000-Rs.5000
and with help of jquery am sending the request to controller..
public PartialViewResult PhonesPartail(int? id,string where)
{
var list = paginateRsult(id, "", where).ToList();
ViewData["totalpages"] = totalPages;
return PartialView("_phonelist",list);
}
and the jquery
$(document).on("change", ".price-checkbox input[type=checkbox]", function () {
if ($(this).is(":checked")) {
var prange = $(this).attr("id");
var parray = prange.split('-');
var whereclause = "price>=" + parray[0] + " and price <=" + parray[1];
$.ajax({
url: '../../Phones/PhonesPartail',
data: { where: whereclause },
type: 'POST',
success: function (data) {
$("#phone-list").append(data);
}
});
}
});
now the list which is returned , is getting added to the div with entire html page.. means again the html page is getting added in the div..
any solution..
Thanks in advance...
use html() function of jquery
It will paste data returned by partial view in to a div rather then appending it to div
$("#phone-list").html(data);

Jquery Accordion Validation Not working when rendering Partial View through $.ajax call

Hi friends,I am working on MVC 4 Razor and I am stuck in a situation
where Employee Personal Details form is to be filled in
steps(wizard)..for which i used jquery accordion control..for every
step i put an accordion..The html in each accordion section is
rendered from partial view through ajax call on every click of
respective accordion (i.e. <h3></h3> tag)..
On page load first/top accordion is active by default. My problem is
to restrict the user to click on next accordion until he/she fills the
presently active accordion correctly..
Here is my full code:
View:
#model XXX.ViewModels.PersonalDetailsViewModel
#{
ViewBag.Title = "PersonalDetails";
Layout = "~/Views/Shared/Template.cshtml";
}
#using (Html.BeginForm("Lifestyle", "Apply", FormMethod.Post, new { id = "personalDetailForm" }))
{
<div class="centerdiv margin_top20">
<div class="row">
#Html.ValidationSummary(true, "Please Correct the following errors:")
</div>
<div style="width: 1000px;">
<div id="Personalaccordion" class="acordion_div" style="padding: 10px; float: left;">
<h3 class="acordion_div_h3" onclick="javascript:PersonalModule.GetRenderingView('Apply/GetBasicDetailsView','personalDetailForm','BasicDetailsDiv');">
<p>
Basic Details<span id="BasicDetailsDivExp"></span>
</p>
</h3>
<div id="BasicDetailsDiv">
</div>
<h3 class="acordion_div_h3" onclick="javascript:PersonalModule.GetRenderingView('Apply/GetPersonalAddressView','personalDetailForm','PersonalAddressDiv');">
<p>
Address<span id="PersonalAddressDivExp"></span></p>
</h3>
<div id="PersonalAddressDiv">
</div>
</div>
<ul id="conlitue_ul" style="margin-top: 20px;">
<li style="margin-left: 140px;">
<input type="submit" class="compareBtn float_lt" value="Continue Buying >" id="continue" /></li>
</ul>
</div>
</div>
}
#Scripts.Render("~/bundles/PersonalDetails")
<script type="text/javascript">
PersonalModule.GetRenderingView('Apply/GetBasicDetailsView', '', 'BasicDetailsDiv');
</script>
My Controller:
public ActionResult PersonalDetails(int leadId)
{
var personalDetailsViewModel = LeadHelper.GetPersonalDetails(leadId);
return View(personalDetailsViewModel);
}
public ActionResult GetBasicDetailsView(PersonalDetailsViewModel personalDetailsViewModel)
{
if (personalDetailsViewModel.BasicDetails == null)
{
ModelInitializerHelper.InitilaizeBasicDetailsVModel(personalDetailsViewModel);
}
ModelInitializerHelper.InitializeBasicLookup(personalDetailsViewModel);
return PartialView("Personal/BasicDetails", personalDetailsViewModel);
}
public ActionResult GetPersonalAddressView(PersonalDetailsViewModel personalDetailsViewModel)
{
if (personalDetailsViewModel.PersonalAddressDetails == null)
{
ModelInitializerHelper.IntializePersonalAddressVModel(personalDetailsViewModel);
}
ModelInitializerHelper.InitializePersonalAddressLookup(personalDetailsViewModel);
return PartialView("Personal/PersonalAddress", personalDetailsViewModel);
}
My JS :
var PersonalModule = {
GetRenderingView: function (url, formId, containerID) {
var applicationurl = ApplicationRoot + '/' + url;
var objects = $('#BasicDetailsDivExp , #PersonalAddressDivExp' );
viewDivID = containerID;
GetAccordionView(applicationurl, formId, objects, containerID, 'accordion_plus', 'accordion_minus');
}
}
GetAccordionView: function (url, formId, objects, containerID, accordion_plus, accordion_minus) {
var formObjectData = null;
if (formId != undefined) {
formObjectData = $("#" + formId).serialize();
}
var renderView = function (data) {
$('#' + containerID).innerHtml = data;
}
ExpandAccordion(objects, containerID, accordion_plus, accordion_minus);
DoServerRequest(url, formObjectData, renderView);
}
ExpandAccordion: function (objects, spanIconID, accordion_plus, accordion_minus) {
var Objects = objects;
Objects.removeClass(accordion_minus);
Objects.addClass(accordion_plus);
$('#' + spanIconID + 'Exp').removeClass(accordion_plus).addClass(accordion_minus);
if (Browser.ie7) {
Objects.css("margin-top", "-22px");
}
}
DoServerRequest: function (url, data, funSuccess) {
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
dataType: "json",
success: funSuccess,
error: function (errorResponse) {
if (errorResponse.readyState == 4 && errorResponse.status == 200) {
renderCurrentView(errorResponse.responseText)
}
else {
alert(errorResponse.responseText);
}
}
});
}
Please somebody help..I have heard lots of good thing about this forum
and this is my first Question...Thanks in advance..
I have removed my jquery validation attempt as it made the code
garbage thing Now I dont know what to write and where to write
If you are trying to validate data that has been added to form via Ajax after page load then you will need to use the rules method and add rules for these new elements. Jquery Validate has no way of knowing about them otherwise.
Example
Once you have loaded your new content via Ajax you need to find each element and add the necessary rules to them.
$('#yourDiv').find(".newElements").rules("add", {
required: true,
messages: {
required: "Bacon is required"
}
});
If you are using unobtrusive validate you may need to add your new elements to that also. See this SO question for more details.
Validating the Form
To check if the fields are valid, you will need to validate the form on click. This can be done using .validate(). You can then check if the form validated using .valid()
Example
$('#yourForm').validate();
if(!$('#yourForm').valid()) {
alert('Bacon is required');
}

Can I Use PartialViewResult with PagedList and show it in a PartialView

Hi everyone I have a question, Can I use PagedList in a PartialViewResult Action and show the result in a PartialView?
Here is some code
Controller Code:
public PartialViewResult CargosPorProyecto(string id, int? page)
{
var cargos = db.Cargo.Include(i => i.Proyectos).Where(i => i.NumProyecto.Equals(id)).OrderByDescending(i => i.Fecha);
if (Request.HttpMethod != "GET")
{
page = 1;
}
var pageSize = 10;
var pageNumber = (page ?? 1);
var onePage = cargos.ToPagedList(pageNumber, pageSize);
return PartialView("ListaCargosParcial", ViewBag.OnePage = onePage);
}
In my PartialView i put this code to show the pagination
<div class="pagination-right">
<div class="span12">
<%: Html.PagedListPager((IPagedList)ViewBag.OnePage, page => Url.Action("CargosPorProyecto", new { page = page }), new PagedListRenderOptions { LinkToFirstPageFormat = "<< Primera", LinkToPreviousPageFormat = "< Anterior", LinkToNextPageFormat = "Siguiente >", LinkToLastPageFormat = "Ăšltima >>" })%>
</div>
</div>
And when i load the page that contains the partialview everything looks good, but when i click in Next ("Siguiente") doesn't load in my partial view.
I hope I explained clearly and thanks for the time.
Regards
You could use AJAX if you want to stay on the same page. For example if you are using jQuery you could subscribe to the click event of the pagination links and then trigger an AJAX request to the corresponding controller action and refresh the partial with the results returned:
$(function() {
$('.pagination-right a').click(function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
// refresh the contents of some container div for the partial
// make sure you use the correct selector here
$('#some_container_for_the_partial').html(result);
}
});
// cancel the default action which is a redirect
return false;
});
});

Resources