Problem binding action parameters using FCKeditor, AJAX and ASP.NET MVC - asp.net-mvc

I have a simple ASP.Net MVC View which contains an FCKeditor text box (created using FCKeditor's Javascript ReplaceTextArea() function). These are included within an Ajax.BeginForm helper:
<% using (Ajax.BeginForm("AddText", "Letters",
new AjaxOptions() { UpdateTargetId = "addTextResult" }))
{%>
<div>
<input type="submit" value="Save" />
</div>
<div>
<%=Html.TextArea("testBox", "Content", new { #name = "testBox" })%>
<script type=""text/javascript"">
window.onload = function()
{
var oFCKeditor = new FCKeditor('testBox') ;
var sBasePath = '<%= Url.Content("~/Content/FCKeditor/") %>';
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ToolbarSet = "Basic";
oFCKeditor.Height = 400;
oFCKeditor.ReplaceTextarea() ;
}
</script>
<div id="addTextResult">
</div>
<%} %>
The controller action hanlding this is:
[ValidateInput(false)]
public ActionResult AddText(string testBox)
{
return Content(testBox);
}
Upon initial submission of the Ajax Form the testBox string in the AddText action is always "Content", whatever the contents of the FCKeditor have been changed to. If the Ajax form is submitted again a second time (without further changes) the testBox paramater correctly contains the actual contents of the FCKeditor.
If I use a Html.TextArea without replacing with FCKeditor it works correctly, and if I use a standard Post form submit inplace of AJAX all works as expected.
Am I doing something wrong?
If not is there a suitable/straight-forward workaround for this problem?

The problem is unrelated to MVC but caused by using FCKeditor in conjunction with AJAX. To fix in the code above I added the following to the submit button's onclick event:
<input type="submit" value="Save" onclick="FCKeditorAPI.GetInstance('TestBox').UpdateLinkedField();" />
For more information see here.

Related

Ajax.ActionLink alternative with mvc core

In MVC5 there is #Ajax.ActionLink that is useful to update just a partial view instead of reloading the whole View. Apparently in MVC6 is not supported anymore.
I have tried using #Html.ActionLink like the following but it doesn't update the form, it return just the partial view:
View:
#Html.ActionLink("Update", "GetEnvironment", "Environments", new { id = Model.Id }, new
{
data_ajax = "true",
data_ajax_method = "GET",
data_ajax_mode = "replace",
data_ajax_update = "environment-container",
#class = "btn btn-danger"
})
control:
public async Task<ActionResult> GetEnvironment(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return PartialView("_Environment",environments);
}
Partial view:
#model PowerPhysics.Models.Environments
this is a partial view
Then I tried using ViewComponents. When the page loads the component works correctly but I don't understand how to refresh just the component afterward (for example with a button):
View:
#Component.InvokeAsync("Environments", new { id = Model.Id }).Result
component:
public class EnvironmentsViewComponent : ViewComponent
{
public EnvironmentsViewComponent(PowerPhysics_DataContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(int? id)
{
var environments = await _context.Environments.SingleOrDefaultAsync(m => m.Id == id);
return View(environments);
}
}
How can I update just a part of a view by using PartialViews in MVC6?
You can use a tag as follows:
<a data-ajax="true"
data-ajax-loading="#loading"
data-ajax-mode="replace"
data-ajax-update="#editBid"
href='#Url.Action("_EditBid", "Bids", new { bidId = Model.BidId, bidType = Model.BidTypeName })'
class="TopIcons">Link
</a>
Make sure you have in your _Layout.cshtml page the following script tag at the end of the body tag:
<script src="~/lib/jquery/jquery.unobtrusive-ajax/jquery.unobtrusive-ajax.js"></script>
ViewComponent's are not replacement of ajaxified links. It works more like Html.Action calls to include child actions to your pages (Ex : Loading a menu bar). This will be executed when razor executes the page for the view.
As of this writing, there is no official support for ajax action link alternative in aspnet core.
But the good thing is that, we can do the ajaxified stuff with very little jQuery/javascript code. You can do this with the existing Anchor tag helper
<a asp-action="GetEnvironment" asp-route-id="#Model.Id" asp-controller="Environments"
data-target="environment-container" id="aUpdate">Update</a>
<div id="environment-container"></div>
In the javascript code, just listen to the link click and make the call and update the DOM.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
var _this=$(this);
$.get(_this.attr("href"),function(res){
$('#'+_this.data("target")).html(res);
});
});
});
Since you are passing the parameter in querystring, you can use the jQuery load method as well.
$(function(){
$("#aUpdate").click(function(e){
e.preventDefault();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
});
I add ajax options for Anchor TagHelper in ASP.NET MVC Core
you can see complete sample in github link :
https://github.com/NevitFeridi/AJAX-TagHelper-For-ASP.NET-Core-MVC
after using this new tagHelper you can use ajax option in anchor very easy as shown below:
<a asp-action="create" asp-controller="sitemenu" asp-area="admin"
asp-ajax="true"
asp-ajax-method="get"
asp-ajax-mode="replace"
asp-ajax-loading="ajaxloading"
asp-ajax-update="modalContent"
asp-ajax-onBegin="showModal()"
asp-ajax-onComplete=""
class="btn btn-success btn-icon-split">
<span class="icon text-white-50"><i class="fas fa-plus"></i></span>
<span class="text"> Add Menu </span>
</a>
Use tag helpers instead and make sure to include _ViewImport in your views folder.
Note: Make sure to use document.getElementsByName if there are several links pointing to different pages that will update your DIV.
Example - Razor Page
<script type="text/javascript" language="javascript">
$(function () {
var myEl = document.getElementsByName('theName');
$(myEl).click(function (e) {
e.preventDefault();
var _this = $(this);
$.get(_this.attr("href"), function (res) {
$('#' + _this.data("target")).html(res);
});
});
});
</script>
<a asp-action="Index" asp-controller="Battle" data-target="divReplacable" name="theName" >Session</a>
<a asp-action="Index" asp-controller="Peace" data-target="divReplacable" name="theName" >Session</a>
<div id="divReplacable">
Some Default Content
</div>

How to pass hidden field value to query string in asp.net view?

I am using asp.net mvc with razor view.I have a scenario where I have to pass the hidden field value to query string and access the value. I've declared the hidden field but the problem is that I cannot access the hidden field.
The declaration of hidden field goes here
#model CloudCashWizard.Models.CashSafeLockViewModel
#{
ViewBag.Title = CloudCashWizard.Resources.Resources.AMSEC;
<input type="hidden" value="#Model.CashSafeLockView.DoorNumber" id="hFieldDoorNumber"
name="hFieldDoorNumber" />
}
Want to access the hidden field here at DoorNo
<a id="LCPrint" href = "#Url.Content("~/Aspx/LockConfiguration.aspx?
CashSafeId="+Model.CashSafeLockView.CashSafeId+"&DoorNo="+Hiddenfield)" class="btn btn-primary
btn-Addbutton"><i class="icon icon-white icon-print"></i>Print</a>
How can I do that?Any help will be appreciated.
M.b that's easier to create form with GET method and it will assemble proper URL by itself, based on fields inside that form.
Example:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Get))
{
#Html.Hidden("CashSafeId", Model.CashSafeLockView.CashSafeId);
#Html.Hidden("DoorNo", Model.CashSafeLockView.DoorNumber);
<button type="button"><i class="icon icon-white icon-print"></i>Print</button>
}
You can use this script:
$(document).ready(function(){
$('body').on('click', 'a', function (e) {
$(e).attr("href", $(e).attr("href") + '&ParamName='+$('#hFieldDoorNumber').val();
});
});

Kendo ui MVC window modal making Ajax call with paramters to controller

I am new to Kendo and I am having a very hard time trying to do this. I followed this demo.
here and got it to work up the part that I wanted to have a text box and a send button in the window modal that the user would have to fill in and click send.
I am able to use Ajax to make the call to my controller but I can't get the information in the modal window to pass to the controller via FormCollection. Here's my window modal template:
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h5 data-idtest="1">#= Id #</h5>
<h2>#= TitleDisplay # - #= ArtistDisplay #</h2>
Input The Day:<input id="TheDayTextBox" name="TheDay" type="text" />
#using (Ajax.BeginForm("TheAction", "Search", new AjaxOptions { UpdateTargetId = "#=Id" }))
{
<button class="btn btn-inversea" title="Log outa" type="submit">Log Offsdfsaf</button>
}
</div>
Controller:
public ActionResult TheAction(string id, FormCollection form)
{
....
}
So how does Kendo pass data to controller inside a modal?
Try putting your input inside of the actual form:
<script type="text/x-kendo-template" id="template">
<div id="details-container">
<h5 data-idtest="1">#= Id #</h5>
<h2>#= TitleDisplay # - #= ArtistDisplay #</h2>
#using (Ajax.BeginForm("TheAction", "Search", new AjaxOptions { UpdateTargetId = "#=Id" }))
{
Input The Day:<input id="TheDayTextBox" name="TheDay" type="text" />
<button class="btn btn-inversea" title="Log outa" type="submit">Log Offsdfsaf</button>
}

list is not refreshed in mvc 3 view

I have an asp.net view which has two partial views. One for edit information and other one for displaying list of changes that were made. When I hit the update button, the list is not updated. I used ajax.begin form. How can I do this?
Main view has like this:
<div class="accountdetails1">
#Html.Action("UpdateAccountDetails", new { dispute = dispute })
</div>
<div>
list of changes
#Html.Action("GetAccountAudit")
</div>
updateAccountDetails is like this in start:
#using (Ajax.BeginForm("UpdateAccountDetails", new AjaxOptions
{
LoadingElementId = "loading",
LoadingElementDuration = 2000,
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
}))
{
and functions are like this:
<script type="text/javascript">
function OnSuccess() {
var div = $('#dvMessage');
div.html('');
div.append('Account Information has been updated.');
}
function OnBegin() {
var div = $('#dvMessage');
div.html('');
}
</script>
to show success or failure of update Do I need to update change list in success method? Please suggest
#Ajax methods works in following way:
#Ajax.ActionLink - requests HTML from pointed action via AJAX and puts result in HTML element with id equals to UpdateTargetId value specified in AjaxOptions.
#Ajax.BeginForm - gets the all inputs and selects and other form elements inside using(Ajax.BeginForm()) { .. } and submits it to specified action (using AJAX) then puts response to HTML element with id specified in AjaxOptions.UpdateTargetId property.
So you need something like
<div id="myContainer" >
#using(Ajax.BeginForm("yourActionToProcessEdits", new AjaxOptions { UpdateTargetId = "myContainer" }))
{
.. Form for edit information
#Html.EditorFor(m => m.EditMe)
...
<input type="submit" value="Update" />
.. Display changes here
#Html.Raw(Model.MyChanges)
}
You need to request the GetAccountAudit action to return the list. The beginform is only requesting the UpdateAccountDetails action.
You could do a jquery ajax request in the onSuccess function to request the GetAccountAudit action and update the html.
Could the two actions be combined so that the list would be returned in the UpdateAccountDetails view?

TinyMCE with Ajax Form in ASP.NET MVC

I have set up a form using TinyMCE in my MVC website. To do this, I have an ajaxForm in a partial view like this:
<% using (Ajax.BeginForm(
(Model.ViewMode == ViewMode.Insert) ? "Create" : "Edit",
new AjaxOptions()
{
UpdateTargetId = CustomerViewModel.WindowContentContainerId,
OnFailure = "addValidation"
//OnSuccess = "refresh"
}))
{%>
bla bla
<p>
<label for="CustomerBaneer">
Baner:</label>
<%= Html.TextArea(CustomerViewModel.FieldPrefix + "CustomerBaneer", Model.CustomerToEdit.CustomerBaneer)%>
<%= Html.ValidationMessage(CustomerViewModel.FieldPrefix + "CustomerBaneer", "*")%>
</p>
<input type="submit" value="Save" class="save" />
<%}%>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas"
});
}
</script>
The tinyMce component render well, and I can change my text in bold, underline, etc.. However, when I click on save, the request is send with the textarea content without its formatting (I have monitored it with firebug). Why? Is there any HTML stripping function enables by default with ajax form?
Thanks.
U need to save text from tinymce to that textArea before submit.
Function OnBegin is too late, so i did it this way:
function tinyToText() {
ed = tinyMCE.getInstanceById('yourId');
if (ed) {
$("#yourId").val(ed.getContent());
}
}
<input type="submit" value="Send" onclick="tinyToText();" />
It looks like you need to add an OnBegin handler to your AjaxOptions to call tinyMCE.triggerSave() before your form submits. I'm more familiar with jQuery, so you may have to fix up the syntax for the Ajax.BeginForm calls.
new AjaxOptions()
{
UpdateTargetId = CustomerViewModel.WindowContentContainerId,
OnFailure = "addValidation",
OnBegin = "preSubmit"
//OnSuccess = "refresh"
}
<script="text/javascript">
function preSubmit() {
tinyMCE.triggerSave();
}
</script>

Resources