Html Encoding in ASP.NET MVC - asp.net

I have the following code in a view (Demo.aspx) within a ASP.NET MVC 2 project:
Demo.aspx:
<% if (!Model.IsValid) { %><%= Model.FirstName %> - <% } %><%= Model.LastName %> -
I am trying to convert it to razor view (Demo.cshtml) in the process of migrating the project from ASP.NET MVC2 to ASP.NET MVC3. After doing some analysis and following the URL: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/ for migration of the webforms to razor view, I drafted the following code equivalent in razor view:
Demo.cshtml:
#if (!Model.IsValidName)
{ #Html.Raw(Model.FirstName)
#Html.Raw("-")
}
#Html.Raw(Model.LastName)
#Html.Raw("-")
But by using the conversion tool : http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790 , I got the following code:
Demo.cshtml:
#if (!Model.IsValidName)
{ #Model.FirstName
#Html.Raw("-")
} #Model.LastName
#Html.Raw("-")
Can anyone help to confirm which of the above is correct?

I would recommend the second approach:
#if (!Model.IsValidName)
{ #Model.FirstName
#Html.Raw("-")
} #Model.LastName
#Html.Raw("-")
The reason for this is for security purposes.
As an example the #Model.FirstName will prevent against an XSS attack where as #Html.Raw(Model.FirstName) is circumventing the encoding and making it possible if a user is allowed to update their own FirstName property.

Related

Passing Data From Controller to View MVC-5

I'm currently stuyding MVC-5 ASP.NET and following this tutorial: https://www.youtube.com/watch?v=Fu9v2MIDlTA
I have successfully created my view and controller and therefore my HeLLO WORLD display. Now I'm currently in part 2 of the tutorial wherein I'm passing my data from controller to View.
Here are the codes:
Home Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult ShowHome()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View("Home");
}
}
}
View:
#{
ViewBag.Title = "Home";
}
<html>
<head>
<title>
WELCOME TO MVC 5
</title>
<body>
<div>
This is my homepage! <br/>
TIME: <%= ViewData["CurrentTime"]%>
</div>
</body>
</head>
</html>
The question is: Why is it that when I type the part:
<% %>, my ide is not reading it? I mean, the speaker in the tutorial is using I think Visual Studio 2013 Ultimate. When he types <% >%, there is intellisense.
I'm using Visual Studio 2013 Express for WEB, when I type
ViewData["CurrentTime"] = DateTime.Now.ToString();
The IDE doesn't recognize it and it prints this as a string. :(
Glenn you got confused between they way on how code blocks where annotated in aspx pages and how they are used in the Razor view engine nowadays.
You can see Razor in action right at the top of your View:
#{
ViewBag.Title = "Home";
}
And thats how you do it. The curly braces are optional, if you use a single expression, so in your case you could just write
<div>
This is my homepage! <br/>
TIME: #ViewData["CurrentTime"]
</div>
Scott Gu has written a pretty good article about the differences between the two systems: http://weblogs.asp.net/scottgu/introducing-razor
As a rule of thumb: If its an .aspx file, use <% %>. If it is a .cshtml or .vbhtml use #{ }

Bootstrap form validation for ASP.NET

i am using bootstrap 3.0 form validation JavaScript code from https://github.com/nghuuphuoc/bootstrapvalidator with ASP.NET and it works fine, but when i add runat server to my form controls it does not work please help me on this problem.
RunAt="server" changes names / id's of controls. Instead of:
...
fields: {
firstname: {
... validiation code
}
}
try this:
fields: {
<%= firstname.UniqueID %>: {
... validiation code
}
}
Or if you are using ASP.net 4.0 and you can guarantee uniqueness in the name, you can add ClientIDMode="Static" to the textbox to prevent ASP.net from appending to your Id.

Covert Razor delegate syntax to WebForms

I am trying to write this style of code from cassette using WebForms. Is this possible?
#{
var message = "Hello World!";
Bundles.AddInlineScript(
#<script>
if (someTest) {
alert('#message');
}
</script>);
}
I haven't managed to find an example of using methods with the Func<Object, Object> parameter in WebForms. Or is this because this only allowed by the Razor view engine?
<% Bundles.AddInlineScript("if (someTest) { ...") %>

ASP.NET MVC CAPTCHA implementation

I am attempting to implement a Captcha on a partial view of a page in my application. I have the captcha being refrenced through web.config as a control. I have used the GenericHandler and Class file from this forum post: http://forums.asp.net/t/1871186.aspx/1
How can I reference the user's input if i am using a simple input tag? Should I use an HtmlHelper instead?
<div class="captcha">
<rhcap:Captcha ID="Captcha1" runat="server"></rhcap:Captcha>
<input type="text" id="UserCaptchaText"><input/>
<%= Html.TextAreaFor(m => m.UserCaptcha) %>
</div>
<%if(Captcha1.Text != /* How can get the users input here?*/ ) {
//display error
}else{
//proceed
}%>
Use NuGet and install Recaptcha for .NET (supports MVC as well)
http://nuget.org/packages/RecaptchaNet/
Documentation is on the site:
http://recaptchanet.codeplex.com/
There are other captchas:
http://captchamvc.codeplex.com/
EDIT:
This project has moved to GitHub
https://github.com/tanveery/recaptcha-net
NuGet Google reCAPTCHA V2 for MVC 4 and 5
NuGet Package
Demo And Document
Web.config File in the appSettings section of your web.config file, add the keys as follows:
<appSettings>
<add name="reCaptchaPublicKey" value="Your site key" />
<add name="reCaptchaPrivateKey" value="Your secret key" />
</appSettings>
Add Recaptcha in your view.
#using reCAPTCHA.MVC
#using (Html.BeginForm())
{
#Html.Recaptcha()
#Html.ValidationMessage("ReCaptcha")
<input type="submit" value="Register" />
}
Verifying the user's response.
[HttpPost]
[CaptchaValidator]
public ActionResult Index(RegisterModel registerModel, bool captchaValid)
{
if (ModelState.IsValid)
{
}
return View(registerModel);
}
EDIT:
You should also add this in your head tag or you might see improper captcha
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
First off, it looks like you are mixing standard ASP.NET and ASP.NET MVC. If you want to do MVC, the standard way to do it is the Html.TextBoxFor() type of stuff, and then you handle the value of that in a controller action method rather than write something inline in the page. So you have something like this:
Page.aspx
<rhcap:Captcha ID="Captcha1" runat="server"></rhcap:Captcha>
<%= Html.TextBoxFor(m => m.UserCaptcha) %>
and then in:
SomeController.cs
[HttpGet]
public ActionResult Page()
{
// generate captcha code here
ControllerContext.HttpContext.Session["Captcha"] = captchaValue;
return View(new PageViewModel());
}
[HttpPost]
public ActionResult Page(PageViewModel model)
{
if (model.UserCaptcha == ControllerContext.HttpContext.Session["Captcha"])
{
// do valid captcha stuff
}
}
To take this to the next level would be to implement it in a FilterAttribute. But this should work for most uses.
I would recommend you to use Google reCAPTCHA, is the best and easy to implement plus it comes with the trust of Google.
Very very effective and easy to implement.
Read this article written by me on implementing Google reCAPTCHA in ASP.NET MVC
Thanks

asp.net mvc view code

I am dynamically generating a table to present some tabular data. Normally I would not go near tables, but for this kind of data it is appropriate.
I am noticing my view code is becoming very spaghetti like. Assigning classes on cells and rows in the body of loops is starting to look just awful (bad flashbacks to my asp 3.0 days).
I looked into using the runtime serialization to json for my DTOs and then using a JQuery plugin for templated rendering of JSON. It seems like a "cool" idea, but is more of a programming exercise than I care to do at the moment.
How are people building more involved UIs with asp.net mvc?
If you're concerned about how your view markup mixed with code looks, you can try an alternate view engine:
Spark
NVelocity
Brail
NHaml
All of these view engines take different approaches to combining code and markup that can make your view markup "cleaner".
I've written some HtmlHelper extensions to help with table building. These extensions use a TagBuilder in code to generate the rows according to the values and HTMl attributes defined. The view code is considerably cleaner using these extension methods and the extension methods themselves are testable to ensure that they produce clean code reliably.
Sample view code:
<% var alternating = false;
foreach (var model in Model) { %>
<% using (Html.BeginTableRow( new { #class = alternating ? "alternating-row" : "" } )) { %>
<%= Html.TableElement( model.Column1 ) %>
<%= Html.TableElement( model.Column2, new { #class = 'some-class' } ); %>
<%= Html.TableElement( model.Column3 ) %>
<% }
alternating = !alternating;
%>
<% } %>
In addition, I've actually create a grid control that will generate a styled table using the above and most of my view code consists of rendering the grid control with the proper model.
<% Html.RenderPartial( "GridControl", Model, ViewData ); %>

Resources