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

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 = "";

Related

MVC c# prevent xss

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.

How to retrieve both Text and Value from DropDownList in Asp.net mvc

I have a dropdownlist in asp.net mvc which is bound using the normal binding syntax
and I can retrieve the "value" in the controller.
But I also need to display the text that is associated with this value.
I can go the hard route and query the db for this associated value.
But I wanted to know if there is an easy way to retrieve the Text as well as the Value in the controller.
Sample code I used
<%= Html.DropDownList("State","Pick a State")%>
which displays
"NJ", "New Jersey" etc.
In Controller
public ActionResult SelectState(string State)
{
// I have value of State (NJ) ...I also need the Text for this
}
Any help would be appreciated.
Thanks
The value that will come as part of the form submission is the value of the dropdown item. To get both, you could change the value to be something like "value delimiter text", so something like "NJ|New Jersey". Then you could parse it in the controller.

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

Model not rendering model values after post

I have an ASP.NET MVC page that has a list of items...
//a vague representation
Model.someValue[0] Model.someHiddenValue[0]
Model.someValue[1] Model.someHiddenValue[1]
Model.someValue[2] Model.someHiddenValue[2]
All fields are optional, but they do have some validation, of which I am showing validation messages.
The problem is, when I submit once and return the original view instead of a redirect, the hidden fields are not getting their new value, but their new value is in the view model being passed to the view.
I am thinking the ModelState might be overriding the model as part of validation. I know I can do a redirect and bypass the problem, but I want be able to save part of the form and show validation errors for the rest. If there are no other solutions, I will simply validate the whole form and only save when all items are valid.
If values are present in ModelState, it shows them instead of the values in your model, since they represent the "last" known state provided from the user.
You should clear out ModelState if you're not actually intending the user to re-do their edits.
Did you try this?:
var newValue = new ValueProviderResult("value", "value", System.Globalization.CultureInfo.CurrentUICulture);
ModelState.SetModelValue("someHiddenValue", newValue);

MVC - How to change the value of a textbox in a post?

After a user clicks the submit button of my page, there is a textbox that is validated, and if it's invalid, I show an error message using the ModelState.AddModelError method. And I need to replace the value of this textbox and show the page with the error messages back to the user.
The problem is that I can't change the value of the textbox, I'm trying to do ViewData["textbox"] = "new value"; but it is ignored...
How can I do this?
thanks
You can use ModelState.Remove(nameOfProperty) like:
ModelState.Remove("CustomerId");
model.CustomerId = 123;
return View(model);
This will work.
I didn't know the answer as well, checked around the ModelState object and found:
ModelState.SetModelValue()
My model has a Name property which I check, if it is invalid this happens:
ModelState.AddModelError("Name", "Name is required.");
ModelState.SetModelValue("Name", new ValueProviderResult("Some string",string.Empty,new CultureInfo("en-US")));
This worked for me.
I have a situation where I want to persist a hidden value between POST's to the controller. The hidden value is modified as other values are changed. I couldn't get the hidden element to update without updating the value manually in ModelState.
I didn't like this approach as it felt odd to not be using a strongly typed reference to Model value.
I found that calling ModelState.Clear directly before returning the View result worked for me. It seemed to then pick the value up from the Model rather than the values that were submitted in the previous POST.
I think there will likely be a problem with this approach for situations when using Errors within the ModelState, but my scenario does not use Model Errors.

Resources