I've been wracking my brain over this problem for a while. How can I invoke a JS function and retrieve the data to be used within a C# method?
Should I be using ViewBag in this example?
.cshtml
<script>
function somefunction(str)
{
//use str within Index() method
return str;
}
</script>
Controller
public IActionResult Index()
{
//use the data within this method
return View();
}
Have you tried this
In javascript function:
//Do your action
window.location.href = '#Url.Action("Index", new { value = 1})';
and modify the Index Action to accept parameter like this:
public ActionResult Index(int value)
As your Index returns a View, window.location.href will basically redirect to Index action.
You can also create an url using string concatenation in javascript and use that url to redirect.
In my case the #Url.Action converts to this URL : '/Home/Index?value=1'.
I have a querystring like this:
http://localhost:2563/Skill?Months=1,2,3,4,5,6,7,8,9,10,11,12&SelectedMonth=8&Year=2016,2017,2018&SelectedYear=2016&....
And I want to pass Months, SelectedMonth, Year, SelectedYear value into Index() of controller (Index is a function takes 0 argument).
And another issue, after Index function completed, I want binding function (in javascript) to run to bind value into dropdownlist by the SelectedMonth, SelectedYear in querystring
Please help. This function helps access the Views by QueryString (not through my website)
Many thanks.
First, the action name is wrong. you should use the following,
http://localhost:2563/index?Months=1,2,3,4,5,6,7,8,9,10,11,12&SelectedMonth=8&Year=2016,2017,2018&SelectedYear=2016&...
instead of
http://localhost:2563/Skill?Months=1,2,3,4,5,6,7,8,9,10,11,12&SelectedMonth=8&Year=2016,2017,2018&SelectedYear=2016&....
second,
You need to pass some parameters.
Here is how:
public ActionResult Index(List<int> Months,int SelectedMonth,List<int> Year, int Year)
{
}
remember to pass values as you wish to work with them. if you don't, you will face some error. use try catch block to prevent and handle exceptions.
You may also face exception accessing the web page. try to put optional parameter instead of using the above one.
public ActionResult Index(List<int>? Months,int? SelectedMonth,List<int>? Year, int? Year)
{
}
public ActionResult Index(List<int> Months,int SelectedMonth,List<int> Year, int Year)
{
}
or use Reqest.QueryString
public ActionResult Index()
{
var months=Reqest.QueryString["Months"];
.
.
.
}
You need to get parameters from here HttpContext.Current.Request.QueryString
I'm trying pass a html code trough Ajax like this:
Using plugin 'summernote' (WYSIWYG Editor)
var description = $('#ticketDescription').code();
This give me for example:
<span style="font-weight: bold;">asdasdasd<span>sadasd
and when Ajax process this give an 500 internal error
$.ajax({
url: '/Ticket/NewTicket',
type: 'POST',
data: {
companyId: companyId,
subject: subject,
ticketDescription: description
},
success: function(result) {
....
},
error: function(result) {
}
});
The problem is solved by removing the '<' character from string.
Any solution to this?
Thanks
Edit: The only way I found so far is:
In javascript:
description = escape(description);
and in the controller:
ticketDescription = HttpUtility.UrlDecode(ticketDescription);
Is it correct?
ValidateInput and AllowHtml attribute is what you need to set in the property
By default Asp.Net MVC doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your application.
ValidateInput Attribute
This is the simple way to allow the submission of HTML. This attribute can enable or disable input validation at the controller level or at any action method.
ValidateInput at Controller Level
[ValidateInput(false)]
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}
[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{
}
return View();
}
}
Now, the user can submit Html for this Controller successfully.
ValidateInput at Action Method Level
public class HomeController : Controller
{
public ActionResult AddArticle()
{
return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult AddArticle(BlogModel blog)
{
if (ModelState.IsValid)
{
}
return View();
}
}
Now, the user can submit Html for this action method successfully.
Limitation of ValidateInput attribute
This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use AllowHtml attribute.
AllowHtml Attribute
This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
public class BlogModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[AllowHtml]
[Required]
[Display(Name = "Description")]
public string Description{ get; set; }
}
Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.
I am using a userControl in MVC 4 that has a telerik radeditor.
I want to submit the content of the radeditor the the action method but if I user editor.get_html() the code doesn't execute.
the javascript call to the action method is the following:
function Save() {
var editor = $find("<%=radEdit.ClientID%>");
var editorHtmlContent = editor.get_html();
var entityId = document.getElementById('hdEntityId').value;
var url = '<%=Url.Action("SaveNote", "staticController")%>';
$.post(url, { EntityId: entityId, Desc: editorHtmlContent }, function (result) { });
}
any clue?
Posting HTML tags is being considered a security threat (HTML Injection and Cross-site Scripting (XSS)), so it is blocked by default. You have three ways out of this:
Encode your HTML on client side before sending to the server. You can find a lot of reading about that on SO, for example here: Fastest method to escape HTML tags as HTML entities?
If you have strongly typed model class and want to get the actual HTML, you can use AllowHtmlAttribute:
public class XMLModel
{
public int EntityId { get; set; }
[AllowHtml]
public string Desc { get; set; }
}
Last option is to disable input validation for entire action, which can be done with ValidateInputAttribute:
[ValidateInput(false)]
[HttpPost]
public ActionResult SaveNote(...)
{
...
}
You should choose the option most suitable for you.
I am using tinyMCE (a rich text editor in js).
Currently, I have a function as such:
function GetEditorValue() {
var val = tinyMCE.get('valueTextArea').getContent()
}
which returns the text that was entered into the rich text editor.
Now, is there a way to pass this data using POST to my mvc controller
and access it there?
(All this is being done in ASP.NET MVC 2 using C#)
You could send this value using AJAX. For example jQuery provides the .post() function:
var val = tinyMCE.get('valueTextArea').getContent();
$.post('<%= Url.Action("foo") %>', { value: val }, function(result) {
// TODO: handle the success
alert('the value was successfully sent to the server');
});
and inside your controller action:
[HttpPost]
public ActionResult Foo(string value)
{
// Do something with the value
}
Now obviously because this is a RichText editor the value might contain dangerous characters and ASP.NET will reject them by throwing an exception. To avoid this you could decorate your controller action with the [ValidateInput(false)] attribute:
[HttpPost]
[ValidateInput(false)]
public ActionResult Foo(string value)
{
// Do something with the value
}
and if you are using ASP.NET 4.0 you should also add the following to your web.config:
<httpRuntime requestValidationMode="2.0" />