Passing HTML string to my controller action method

I am using a rich text editor to type formatted text, as shown below:

I am using a rich text editor to type formatted text, as shown below:

I can get the HTML formatted text, which would look like this:

<p>This is my rich HTML Text</p>

Now I want to pass this HTML formatted text to my controller and my controller would put the text in an email and send it to the receiver.

The problem is HTML string is considered unsafe, so in order to pass it to my controller, I need to add [ValidateInput(false)] attribute to my Action method, like below:

    [ValidateInput(false)] // <-- not able to hit the action method without this
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<JsonResult> Contact(string message)
    {
        if (!HttpContext.User.Identity.IsAuthenticated)
        {
            return Json(new { Authorize = "false" });
        }
    // email message to receiver
}

And this is the Ajax method which contacts the controller:

$('#contactBtn').click(function () {
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var message = quill.root.innerHTML; // <-- HTML formatted message

$.ajax({
    url: "/Communication/Contact",
    data: { __RequestVerificationToken: token, message: message },
    dataType: 'json',
    type: "POST"
});

});

So the above code works, but I am not sure if this is the right thing to do? Is there any security issue with the above code? Is there any encoding that I need to do on the HTML?

ASP.NET MVC Application with JQuery, AJAX

ASP.NET MVC Application with JQuery, AJAX

Let's have a sample example: We have a submit button in our JQuery AJAX MVC application. Let's try to show a message when it is clicked. ASP.NET MVC Application - Using JQuery, AJAX

Before diving into the core topic let’s have an overview about JQuery and Ajax. What is it?

What is JQuery?
Well, JQuery is a framework (tools) for writing JavaScript, Written as "write less, do more", jQuery is to make easier to use JavaScript.

What is JavaScript?
JavaScript is an object-oriented computer programming (Scripting) language commonly used to create interactive effects within web browsers.

Let’s have a sample example:
We have a submit button in our JQuery AJAX MVC application. Let’s try to show a message when it is clicked.

Here is our button with defined id="btnSubmit":

<input type="submit" value="Create" class="btn btn-default" id="btnSubmit" />

Now we need to write some script to do that, here is some JavaScript code:

var myBtn = document.getElementById('btnSubmit');  
myBtn.addEventListener('click', function(e) {  
    e.preventDefault(); //This prevents the default action  
    alert('Hello'); //Show the alert  
});

By this code the result will show “Hello”:

Now if we can get the same result by using jQuery instead of it. Let’s have a look:

$('#btnSubmit').click(function(event) {  
    event.preventDefault(); //This prevents the default action  
    alert("Hello"); //Show the alert  
});

Note: Here use of 'e' is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part.

This piece of code is also producing the same result “Hello”. This is why jQuery is known as "write less, do more".

Finally the script:

<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
  
            /*var myBtn = document.getElementById('btnSubmit');  
            myBtn.addEventListener('click', function(e) {  
                e.preventDefault();  
                alert('Hello');  
            });*/
  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                alert("Hello");  
            });  
        });  
    });  
</script>

Let's focus on Ajax:

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.

In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on JQuery Ajax.

$.ajax () Method:

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() Performs an async AJAX request.
  • $.get() Loads data from a server using an AJAX HTTP GET request.
  • $.post() Loads data from a server using an AJAX HTTP POST request.

To know more click.

$.ajax () Method Configuration option:

Options that we use:

  • async:
  • type:
  • url:
  • data:
  • datatype:
  • success:
  • error:

Let’s have details overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

Note that if you set this option to false, your request will block execution of other code until the response is received.

Example:

async: false,

type

This is type of HTTP Request and accepts a valid HTTP verb.

The type of the request, "POST" or "GET" defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all the web browsers.

Example:

type: "POST",

url

The URL for the request.

Example:

url: "/Home/JqAJAX",

data

The data to be sent to the server. This can either be an object or a query string.

Example:

data: JSON.stringify(model_data),

dataType

The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.

Accepted values are text, xml, json, script, html jsonp.

Example:

dataType: "json",

contentType

This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.

Example:

contentType: 'application/json; charset=utf-8',

success

A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the DataType was JSON), as well as the text status of the request and the raw request object.

Success: function (result) {  
   $('#result').html(result);  
}

error

A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

error: function (result) {  
   alert('Error occured!!');  
},

Let’s Post Values using JQuey,Ajax:

We often use the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:

<input type="submit" id="btnSubmit" value="Add Student" />  
<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                var Student = {  
                    ID: '10001',  
                    Name: 'Shashangka',  
                    Age: 31  
                };  
                $.ajax({  
                    type: "POST",  
                    url: "/Home/JqAJAX",  
                    data: JSON.stringify(Student),  
                    dataType: "json"  
                    contentType: 'application/json; charset=utf-8',  
                    success: function(data) {  
                        alert(data.msg);  
                    },  
                    error: function() {  
                        alert("Error occured!!")  
                    }  
                });  
            });  
        });  
    });  
</script>

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Posting JSON

JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:

JSON.stringify(Student)

And the data type set to:

datatype: "json"

And the content type set to application/json

contentType: 'application/json; charset=utf-8'

Syntax:

JSON.stringify(value[, replacer[, space]])

Post Script:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: JSON.stringify(Student),  
    contentType: 'application/json; charset=utf-8',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

JSON Response Result:
Sent data format:
{"ID":"10001","Name":"Shashangka","Age":31}
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Objects:

To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default.

contentType: 'application/x-www-form-urlencoded'

Post Script

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

JavaScript Objects Response Result:

Sent data format:
ID=10001&Name=Shashangka&Age=31
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Arrays:

To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default

contentType: 'application/x-www-form-urlencoded'

Post Script:

var ID = ["Shashangka", "Shekhar", "Mandal"];  
  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: {  
        values: ID  
    },  
    datatype: "html",  
    contentType: 'application/x-www-form-urlencoded',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(string[] values) {  
    try {  
        return Json(new {  
            msg = String.Format("Fist Name: {0}", values[0])  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Array Response Result:

Sent data format:
values[]=Shashangka&values[]=Shekhar&values[]=Mandal
Received Data format:
{"msg":"Fist Name: Shashangka"}

Hope this will help to understand different datatypes and Ajax posting. Thank you!

Asp.Net Core MVC Bangla Tutorials -01 (Complete eCommerce Application)

Asp.Net Core MVC Bangla Tutorials -01 (Complete eCommerce Application)

LIKE | COMMENT | SHARE | SUBSCRIBE The easiest way to start coding in Visual Studio is by creating a new project from a template – we’ll cover working with e...

How to use FileUpload control inside ASP.Net AJAX Update Panel

There are plenty of questions asked by developers around the globe that they are not able to use FileUpload asp.net control inside ASP.Net Ajax update panel. Their issues are FileUpload control inside Asp.Net Ajax update panel doesn’t hold any file and also return false for HasFile property whenever they upload any file.

There are plenty of questions asked by developers around the globe that they are not able to use FileUpload asp.net control inside ASP.Net Ajax update panel. Their issues are FileUpload control inside Asp.Net Ajax update panel doesn’t hold any file and also return false for HasFile property whenever they upload any file.

Don’t worry! This is because the uploading and manipulations of files are restricted by default in client side for security purpose. That’s why this is not possible to upload files using asynchronous postback in UpdatePanel. you can do it just by changing the Trigger of the upload button from AsyncPostBackTrigger to PostBackTrigger.

Note – Asp.Net Controls that are reside in updatepanel, cause an async postback/update by default. That’s why the page will postback and get partial rendering. Now if for any reason you have control inside an updatepanel which you have to make a full postback rendering, then you need to set it explicitly as a postbacktrigger.

ASP.Net Webform(Aspx) Code :

To use ASP.Net Ajax, you have to add reference ajaxcontroltoolkit.dll in your solution first then you can use below code to upload a file.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileUpload.aspx.cs" Inherits="Open_FileUpload" %>
<!DOCTYPE html>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>  
        <div>
            <asp:UpdatePanel ID="up1" runat="server">
                <ContentTemplate>
                    <asp:FileUpload ID="fileUpload" runat="server" />
                    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    <br />
                    <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
                </ContentTemplate>
                <Triggers>
                    <asp:PostBackTrigger ControlID="btnUpload" />
                </Triggers>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

Code behind .cs code :

For demo purpose, I am trying to allow the user to upload only jpg or jpeg images.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        if (fileUpload.HasFile)
        {
            string fileExt = System.IO.Path.GetExtension(fileUpload.FileName);
            if (fileExt.ToLower() != ".jpg" && fileExt.ToLower() != ".jpeg")
            {
                lblMsg.Text = "Upload JPG images only.";
                lblMsg.ForeColor = System.Drawing.Color.Red;
                return;
            }            
            filePath = fileUpload.PostedFile.FileName;
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            fileUpload.PostedFile.SaveAs(Server.MapPath(@"../UploadedImages/" + filePath.Trim()));          
        }


by RAVI RANJAN KUMAR