MVC c# prevent xss - asp.net-mvc

I have a simple email form on my site with mvc c#.
If i added into the text box alert("test") I get the below exception:
A potentially dangerous Request.Form value was detected from the client (Message="<script>alert("test"...").
I dont want a user to be able to insert javascript. I need for html encode i would i do this on this field
#Html.TextAreaFor(model => model.Message, new { #style = "width:800px;height:300px;" })

Option 1: look at the accepted answer at:
HTML-encoding lost when attribute read from input field
Option 2: Put the [AllowHtml] attribute on the model item that binds to this textbox and that will let the value into your controller where you can use HtmlEncode.
Option 3: Put the [ValidateInput(false)] attribute on your controller action, this lets everything through no matter what and then you can do your own custom validation for everything

Use System.Web.HttpUtility.HtmlEncode to encode all user input and avoid XSS atacks.

Related

About binding a checkbox to string property in MVC viewmodel

In my project I have a string field in the view model to display in a form and post back to the controller.
However for some reason, I'd like to display a checkbox, and retrieving string "True"/"False" from user input
I've searched through the internet and found this
How to render a model property of string type as checkbox in ASP.NET MVC
which leverage the editor template and achieve my need.
My question is that how do this be achieved, because in the editor template, I can only see it how to interpret the string to a checkbox, but it never explain or show how the checkbox value will be bind back to the string field with "True"/"False".
What should I do if I wanted "Yes"/"No" instead of "true"/"false", are there any converter that I need to make to parsing the checkbox to string?
Sorry for my bad English and lack of mvc knowledge, I just started MVC and web development for a few days.
UPDATE:
1. I am using ViewModel to bind with the forms, so I need something like Html.CheckBoxFor(x=>x.value)
while x.value is a string, obviously it is not possible with the default CheckboxFor
I think what you are asking is how to save the value back into your database, which is more of a back-end C# or VB question.
As you know, when you submit a form on an HTML page, if a checkbox is ticked, it's value will be passed in the POST parameters back to the server:
front-end HTML:
<input type="checkbox" name="theCheckBox" value="Yes" />
back-end C# in Page_Load() or similar
if(Request.Form["theCheckBox"] == "Yes") {
// save value "Yes" into database
}
just remember that if the checkbox is NOT TICKED, Request.Form["theCheckBox"] will be null

asp.net mvc disabled text box updated by javascript does not post new value

I am using a strongly typed model for my view. I have a disabled text box whose value I update using javascript. The textbox is rendered using this
<%: Html.TextBoxFor(model => model.TotalAmount, new { disabled = "disabled"})%>
This renders a textbox with NAME and ID as 'TotalAmount'. TotalAmount is also a property on my model that binds to this view.
The javascript to update its value in the view is like this within its function:
document.getElementById('TotalAmount').value = {assigning new value here};
The function does get called and I can see the value in the disabled textbox when I change some value in another editable textbox. However, when I post this form to my action method as below :
[HttpPost]
public ActionResult Process (ProcessVM FormPostVM)
{
}
the disabled textbox property [TotalAmount] still has the old value but the editable textbox which I modified contains the new value I entered. Why does the disabled textbox not contain the javascript updated value?
I tried using
ModelState.Remove("TotalAmount");
in the action method above, but as I already figured it didn't work.
Any clues, tips?
Thanks for your time....
HTML input elements such as textboxes that have the disabled="disabled" attribute will never send their values to the server when the form is submitted. If you want to send the value to the server while still disabling the user from changing it you could make the textbox readonly:
<%= Html.TextBoxFor(model => model.TotalAmount, new { #readonly = "readonly" }) %>
Disabled inputs are never sent in a form submit, try using readonly attribute instead or hidden inputs
Disabled fields don't get posted. Try having a hidden form field that will send the value to the server, and set both TotalAmount and the hidden form field. On the server, use the value for the hidden field instead.
On a side note, since this looks like the order total, this is something I would recalcuate on the server rather than opening up the possibility of someone hacking the html and getting a discount on their product.
EDIT:
To the other's points, I'd forgotten about the readonly attribute. That will work too.
If you change it to use readonly rather than disabled, then this should give you the same functionality, but post the value.
Browsers don't post values back in disabled input controls, as you've discovered. Probably the easiest way to work around this is to hook onto form submission, and re-enable the input as the form is being submitted; the user won't have a chance to edit the value, and it should get posted with the rest of the request.
i think the last issue described it : please check it out :
Retrieving the value of a asp:TextBox

ASP.NET MVC reading an element's custom html attribute when submitting

I'm new to ASP.NET and MVC in particular.
Now, I'm trying to understand if I can easily get values of custom attributes of submitted data.
For example, When writing something like this inside a form (which works and posts and I can get the checkbox value)
<%= Html.CheckBox("cb1", new { listen = "listen:6" }) %>
Can I get the value of "listen" directly or do I need JS?
(I know I can just use hidden fields, but I'm I'm asking anyway)
Thanks
You cannot; when a form is POST-ed, only the name/value pairs are sent. This is a general feature of HTML and forms, and not specific to ASP.NET or MVC.

Asp.net MVC add textbox value to routelink

I am trying to learn asp.net MVC and having an issue to submit a textbox value to a model.
I have a text box in which users will type a number and when they hit the routelink the routelink will take the value from the textbox and assigns it to one of .Page item.
<%=Html.TextBox("PageIndex")%>
<%=Html.RouteLink("Search", "UpcomingEvent",
New With {.Page = "I want to put value of PageIndex textbox here"})%>
How can I assign the value of the textbox to .Page variable?
Thanks for your time and help!
You can't do that because the RouteLink gets rendered on the server.
If you want to construct a URL based on the user input without a postback, you'll need to do some client-side scripting (ie JavaScript).
It sounds like you're not expecting to post back to the server once they have the textbox value entered. If that is the case then you're going to need to use javascript to change the link's href property. Html.RouteLink is all done server side.
If you are using jquery then it would be something like
$("#pageIndex").change(function()
{
$("#pageLink").href += "?pageIndex=" + $("#pageIndex")"
}
Of course that isn't going to work with multiple change events being fired but that part is left as an exercise for the reader.

How to clear the post data for a textbox in an ASP.NET MVC application?

By default, a textbox rendered using <%= Html.TextBox("somefield")%> uses the value from the post data, e.g. if you have validation errors on your page, the value is retrieved from the posted data and used for the value attribute.
Now, in a few cases I want to be able to clear that value, in other words I want the textbox to be blank, I don't want MVC to get the value from the posted data and uses it for the value attribute, how can I do? How can I clear the post data?
Thanks
ModelState.Remove("key");
Remove the value from the model state, like this:
ViewData.ModelState.Remove("somefield");
I found I had to both remove the ModelState and change the model, as if MVC tries ModelState first, then the model:
ModelState.Remove("key");
model.key = "";
And if you don't want to lose your Error state for the model, you can just change the value like this:
ModelState.SetModelValue("Captcha", new ValueProviderResult(null, string.Empty, System.Globalization.CultureInfo.InvariantCulture));
model.key = "";

Resources