I want to set a html content to TinyMCE editor content in ASP.NET MVC
so I come come with a solution that convert that HTML file to string in server side and then call it using ajax in client side
this is C# controller method
[HttpGet]
public string TyneMice()
{
return System.IO.File.ReadAllText(#"C:\Users\..\myhtml.html");
}
this is ajax call ,
<script type="text/javascript">
tinymce.init({
...,
setup: function (ed) {
ed.on("init", function (ed) {
$.ajax({
type: "GET",
url: "Brochure/TyneMice",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
tinyMCE.activeEditor.setContent(data);
},
error: function () { alert("Ajax Error"); }
});
})
}
});
</script>
But Once I put debug point on above string method it is not invoking
Then I put above script inside $( document ).ready(function() { ... }
But the same result it doesnt work.
Your Action should return of type ActionResult. The action will return Json object with JsonRequestBehavior set as AllowGet.
[HttpGet]
public JsonResult TyneMice()
{
return Json("TyneMice Example", JsonRequestBehavior.AllowGet);
}
Related
I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}
I am having some issues calling a controller method from my jquery ajax. The controller method is called and the data servername is passed in correctly. But, before my controller can return anything to the jquery, the jquery enters the error state.
Here is my jquery and controller code snippets:
$.ajax({
type: 'POST',
url: '#Url.Action("serverLookup", "QC")',
dataType: 'text',
data: { 'serverName': servername },
success: function (result) {
alert(result);
debugger;
},
error: function (result) {
debugger;
}
});
[HttpPost]
public ActionResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Content(data);
}
On top of everything. The result value given when the error is reached is not helpful at all either.
Send your response back as JsonResult
[HttpPost]
public JsonResult serverLookup(string serverName)
{
string data = myMethod.getData();
return Json(data);
}
Return a Json:
return Json(new { result: data });
When you make an AJAX request to the controller, it needs a JsonResult.
I suppose that Your Content() return html. In that case You have to change dataType to html, Or change it according to your response.
Hello I'm posted a question asking what to use to send information from a view to a model. I realize that the info needs to be send to the controller and then to my model. I got some code that send info from my view to my controller:
Here is the Ajax:
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content fom the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
alert(data);
},
error: function (e) { alert(e); }
})
});
});
An this is the code in my controller:
[HttpPost]
public ActionResult processCommand(string cmd)
{
return Json(cmd);
}
I've tested it and send my input in json. However my problem is, I don't know how to take the string out of that and send it to my model. Please any help would be appreciated.
As stated in the comments to your question, the terminology you use is a little confusing, but if understood your question correctly, you want an action on your controller on the server to accept a 'command' and work with it.
The following post can be made, in order for the ajax post to successfully hit the action :
$('#cmdSend').click(function () {
var cmdInput = document.getElementById('cmdInput').value;
$.ajax({
url: 'terminal/sendInfo',
type: 'POST',
data: {cmd : cmdInput},
dataType: 'json',
success: function (data) {
//What you want to do with the returned string with data.cmd
}
});
});
The controller action would be like the following :
public class TerminalController : Controller
{
[HttpPost]
public JsonResult sendInfo(string cmd)
{
//Do what you want to do with 'cmd' here.
return Json(new { cmd = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps!
I'm using MVC 4 and I am trying to send a post request and I am getting a successful return from my controller with the resulting view in HTML form, but I'm not sure what to do with it at that point.
JS
$("form").submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
}
});
my controller
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
So you can see that my controller either returns a View or a RedirectToAction. In the success callback of my ajax call I am doing the following: $("#content").html(data);
But nothing seems to happen. Can someone help push me in the right direction of properly handling the return of the controller action.
Thank you so much!
If I understand correctly, you have a Create Event form on your page and you want to send an AJAX request to create a new event. Then you want to replace a section in your page #content with the results of the CreateEvent action.
It looks like your AJAX is set up correctly so that CreateEvent returns a successful response. I think you're now confused about the response. You have several options but let's choose two.
JSON response
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return Json(event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
...
Now you need to generate html markup from the JSON and insert it into #content.
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
var obj = JSON.Parse(data);
var html; // build html with the obj containing server result
$("#content").html(html);
}
})
or HTML fragment
Instead of returning a full page with a Layout defined we'll return just a PartialView without Layout and all the head and script tags.
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return PartialView("CreateEventResult", event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
}
Now make a new partial view CreateEventResult.cshtml (Razor)
#model Namespace.EventModelResult
# {
Layout = null;
}
<div>
<!-- this stuff inserted into #content -->
#Model.Date
...
</div>
and the javascript is unchanged
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
Edit:
If your Event creation fails for any reason after you have validated the input, you'll have to decide how you want to respond. One option is to add a response status to the object you return and just display that instead of the newly created Event.
Index.html (View)
<div class="categories_content_container">
#Html.Action("_AddCategory", "Categories")
</div>
_AddCategory.cshtml (PartialView)
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
$(".categories_content_container").html(result);
},
error: function () {
}
});
});
});
</script>
#using (Html.BeginForm())
{
// form elements
}
Controller
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return RedirectToAction("Categories");
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
Question: If operation is success I expect that redirect to another page (Categories). But no action, no error message. If operation is not success, it is working like my expected.
How can I do this? How can I route another page with using AJAX post?
Don't redirect from controller actions that are invoked with AJAX. It's useless. You could return the url you want to redirect to as a JsonResult:
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return Json(new { redirectTo = Url.Action("Categories") });
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
and then on the client test for the presence of this url and act accordingly:
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
// The operation was a success on the server as it returned
// a JSON objet with an url property pointing to the location
// you would like to redirect to => now use the window.location.href
// property to redirect the client to this location
window.location.href = result.redirectTo;
} else {
// The server returned a partial view => let's refresh
// the corresponding section of our DOM with it
$(".categories_content_container").html(result);
}
},
error: function () {
}
});
Also notice that I have gotten rid of the dataType: 'json' parameter from your $.ajax() call. That's extremely important as we are not always returning JSON (in your case you were never returning JSON so this parameter was absolutely wrong). In my example we return JSON only in the case of a success and text/html (PartialView) in the case of failure. So you should leave jQuery simply use the Content-Type HTTP response header returned by the server to automatically deduce the type and parse the result parameter passed to your success callback accordingly.
The ajax call you made should not be able to redirect the whole page. It returns data to your asynchronous call only. If you want to perform a redirect, i
the javascript way to redirect is with window.location
So your ajax call should look like this:
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
window.location='#Url.Action("Categories")';
},
error: function () {
}
});
});
});
</script>
In you action method, instead of returning a partial or redirect, return Json(true);
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
return Json(true);
}
else
{
return Json(false);
}
}