How to pass HTML element in view to controller class.
Allow html element in MVC form
In this article we will learn how to pass HTML element in
MVC web form. Generally if we put any HTML tag within HTML form and try to pass
data to controller, it will not allow us to send.
But sometimes requirement demands us to pass HTML element in server, or
if we want, we can pass it. Let’s learn with small example.
Create model class.
Here we will create small Article class as our model class.
It has two attributes called Title and content. We did not specify any validation
attribute on our model class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVCTest.Models
{
public class Article
{
public String Title { get; set;}
public String Content { get; set;}
}
}
Create controller class
In this controller class we will talk with view. This class
has two actions, called Index which will call one web form and another one is
GetData.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTest.Models;
namespace MVCTest.Controllers
{
public class ArticleController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetData()
{
if (ModelState.IsValid)
{
String Title = A.Title;
String Con = A.Content;
return Content ("Title is :-" + Title +"Content is :-"+ Con);
}
else
return Content("Not Valid");
}
}
}
When the form is submitted, it will get call. Within
GetData() function we are checking model’s state with IsValid property.
Create view
Now, we will create a simple web form with two text boxes
and one submit button.
@model MVCTest.Models.Article
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm("GetData", "Article", FormMethod.Post))
{
@Html.LabelFor(m=>m.Title,"Title")
@Html.TextBoxFor(m=> m.Title)
@Html.LabelFor(m=>m.Content)
@Html.TextBoxFor(m => m.Content,"Content");
<input type="submit" name="Submit" value="submit" />
}
</div>
</body>
</html>
In form submission,
we are calling GetData action of Article controller.
Here is
output.
If we try to pass any HTML element in form. We will get below output.

OK, we are
getting error. Because by default MVC engine will not allow us to pass html
element from user’s interface.
Solution:-
Just change model class like below
public class Article
{
[AllowHtml] public String Title { get; set;}
[AllowHtml] public String Content { get; set;}
}
We are adding AllowHtml attribute with each property. And
now it will allow us to pass html component.

We have inserted HTML element(<b>) into title tag and trying to submit it.

We are not getting error.
Conclusion:-
In this article we have learned how to allow HTML element in MVC application. But it is not recommended to send HTML element due to security reasons.