Remove browser autocompletion in MVC - c#

I am currently trying to remove the form autocompletion done by the user's browser which can cause some critical behavior since it fills the password field. I have already added the autocompletion attribute to all of my textbox fields but when I try with firefox it stills load my current login information into the fields.
Does anyone know how to resolve this issue?
EDIT: Since it's not clear, I have already added the aucompletion attribute with the value set to "off".

There is an autocomplete=off property in html.
It is used in the top right search box on this very page, inspect the html you'll see:
<input autocomplete=​"off" name=​"q" class=​"textbox" placeholder=​"search" ..... />
See this MDN article: https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion
In MVC you would implement this at the form or for a textbox like so:
Html.BeginForm(
action, controller, FormMethod.Post, new {autocomplete="off"})
OR
Html.TextBoxFor(model => model.EmployerNumber, new {autocomplete="off"})

If you check HERE, setting autocomplete="off" on the form should do the trick.

The HTML5 have a add-on syntax for form/input elements, it is called autocomplete="off".
See http://www.w3schools.com/html5/att_form_autocomplete.asp

You can randomize id and name attributes of your textboxes - this will make browser autocomplete functions not working.
My implementation
In view:
<%
var guidString = Guid.NewGuid().ToString();
%>
<%=Html.TextBox(guidString, String.Empty)%>
<%=Html.Hidden("NameGuid", guidString) %>
in Controller:
string userName = Request[model.NameGuid];
...

Related

Selenium Automation unable to enter username in Way2Automation website

I am trying to do registration for this site
Registration page is inside a popup page.
HTML Code:
<fieldset>
<label>Username:</label>
<input name="username" required="" type="text"/>
</fieldset>
When I try to find the element using below tried code, element is not getting find.
driver.FindElement(By.XPath(".//*[#id='load_form']/fieldset[1]/input")).SendKeys("Kal");
I have also tried this with using CssSelector, but facing the same issue.
driver.FindElement(By.CssSelector("div#load_box form#load_form input[name=username]")).SendKeys("kal");
When I execute above code, I have got an error like element not visible
Can anyone help me on this issue?
Try this below code using xpath locator
driver.FindElement(By.XPath("//input[#name='name']")).SendKeys("Kal");
Explanation of xpath:- Use name attribute of <input> tag.
Suggesstion:- Instead of using absolute xpath, use relative xpath.
Note:- Before reach to this web-element provide some few seconds of wait, so your driver may able to find the web-element. So, you will not get an error like element not visible
Use below xpath:
//*[#id='load_form']/fieldset[6]/input[#name='username']
that site has 2 forms with the id load_form so you're getting the first one which isn't visible since it's the login form. You want the second one which is the register form.
you can use a selector to grab one of the fields that exists on the registration page and then move up to it's parent form and get all descendants that are fieldsets to fill out.
Here is the xpath you can use to pass the text "Dev" into the field labelled with "Name".
driver.findElement(By.xpath("//div[#class='fancybox-overlay fancybox-overlay-fixed']//form[#id='load_form']/fieldset/input[#name='name']")).sendKeys("Dev");
Let me know if this answers your question.
The problem is that there are two username INPUT fields. The way I typically handle this is to find a parent of the element that I want that has an ID or something unique that will distinguish the two elements. In this case, you can use a simple CSS selector,
#load_box input[name='username']
Note the load_box ID that distinguishes the two INPUTs.
Ajax popup on way2automation site is a tricky one because if you look for the username field by name By.name("username"), you will end up with 2 elements - one for username from signup popup, one from singin popup. To avoid this you have to explicity mention the correct element. This can be done via the following code:
webDriver.get("http://way2automation.com/way2auto_jquery/index.php");
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a[href='#login'"))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".ajaxlogin input[name='username']"))).sendKeys("my_username");
As you can see in the code I am using class of the login popup - .ajaxlogin. I have used Java, but the concept is the same - you have to refer to the username element via css selector with popup class included: By.cssSelector(".ajaxlogin input[name='username']")

Adding AntiForgeryToken to non-Ajax Form Submit

I found plenty of examples that demonstrate how to add an AntiForgeryToken to the Ajax call for POST submit method. My need, as the title suggests, is to submit a form NOT via the ajax call. Instead, I'm simply using jQuery submit() function.
What I have in my razor view file is as follows (Note: I'm using html string literal because this particular DOM needs to be dynamically attached to a separate element at a later point):
var html =
"<form id='exportPdfForm' action='" + exportUrl + "' method='post'>" +
"<input type='hidden' id='exportContent'>" +
"<input type='hidden' id='__RequestVerificationToken' value='#Html.AntiForgeryToken()'>" +
"</form>";
And, obviously, I'm using the following jQuery to submit this form:
$("#exportPdfForm").submit();
Also, using the DOM Explorer I can see the AntiForgeryToken value is properly in place:
However, when I actually submit the form, I still run into the The required anti-forgery form field "__RequestVerificationToken" is not present error. I checked out several other Q&A's but can't seem to find anything that might shed some light on my problem.
Am I missing something obvious or doing something wrong here?
EDIT (Solution)
Assigning the __RequestVerificationToken to the name attribute will fix it:
<input type='hidden' name='__RequestVerificationToken' value='...'>
This one turns out to be one of those "How did I miss that...?!" moments. While the above approach is perfectly legitimate, the only problem is that the __RequestVerificationToken has to belong to a name attribute instead of to an id as in my initial example. I tried posting my form with the fix and the problem is now gone.
Obviously this wouldn't have been an issue in the first place if I could just use the <% Html.AntiForgeryToken(); %> expression, but this particular case required an unconventional approach for the reason I stated in my initial post. So, I guess this is something to look out for!

MVC4: How do I get value from partial view for insert/edit

I am new to MVC and I am just trying to get a grip on certain aspects of MVC that I will be using in the project I have coming up. So, I have a view where the user will input data regarding training: name, id, location, and training dates. I have created partial view that will be used for the dates, it incorporates the jQuery date picker and a date mask. This pv will replace date fields where needed. It all works fine, but, I do not know how to get the value placed in the partial view to be passed back into the model, once the user clicks the "Create" or "Edit" button.
Here is my code (Edit View):
#Html.Partial("partialview", Model.ValueToPass)
And For the partial view:
#model Nullable<DateTime>
#{
string dt = string.Empty;
if (Model != null) { dt = Model.Value.tostring("MM/dd/yyyy"); }
<script type="text/javascript">.......</script>
<p> #Html.TextBox("Test", dt, new {#class = "DateTextArea"}) </p>
As stated, I can get a preexisting date from the model loaded into the textbox, without issue, its just retrieving that value or new value, if the user enters a new date, and putting it into the database. Any help or direction would be of great help. Thank you.
If the partial view is within a form element at the top level page, then it will be posted back as if it was part of the original form.
Think of a partial view as being only used at render time. By the time you see the page in your browser, think of it as being one complete page (Not groups of partial views). So any page submit will be done with the whole form in mind.
SOLVED:
I'd like to thank each of you for your inputs as they did help me in finding a solution. The main part I was missing was this:
#Html.Partial("partialview"), Model.ValueToSend, new ViewDataDictionary(ViewData) {
TemplateInfo = new System.Web.Mvc.TemplateInfo {HtmlFieldPrefix = "ValueToSend"
})
I was missing the templateinfo portion on the parent view. Also, I did change my textbox to TextBoxFor and used:
TextBoxFor(model => model, new { #class = .....)
DO NOT go with model.Value, as I had that in there earlier and was still retrieving a null date value on postback. The solution code does not require a hidden field to be populated, the templateinfo code adds an id to the input field in the partial view and the parent controller automatically grabs the data in the partial's input field to get sent to the database, as if it were one of the other auto generated elements on the parent view.
To make the hidden field idea work, with multiples of the same partial view on the parent view, set the hidden field and date textfield (in this example) to the same id; the hiddenfield you'd put an h in front of it ( e.g. date and hdate). Then you'd need to set a javascript variable to get the id of the active element
var id;
($(".datepickerclass").change(function(){
id = $(this).attr('id');
)}
Additionally, if you're using the datepicker
$(".datepickerclass").datepicker(
.....
beforeShow:
id = $(this).attr('id')
And then add the value to the correct hidden element within the change or blur event of the textbox or within the datepicker:
onSelect:
var val = $(id).val()
$('#h'+ id).val(val)
Pardon if the jQuery may be off a bit, I shut down my development machine and I'm typing this without fully testing the jQuery code, but I think you'd get the point. Thanks again for all the help. Next up will be tackling a jQuery grid.
Edit:
Unfortunately since my rating is not high enough, I cannot upvote the answers provided, as they deserve to be.
Use #Html.TextBoxForModel instead of #Html.TextBox(....). This will cause the input to be created with the correct name so that it will bind correctly to your model when you post the page.
You don't need to format the date yourself, you can use the dateFormat option on the jQuery date picker to format the value.
If you use EditorForModel instead of TextBoxForModel, it will create the input with the correct type to use the browsers built in date picker, if available. You can then use Modernizr to test if dates are supported and use the jQuery date picker if it is not. Here is a decent tutorial about it.
You have to be aware that anything you do with C# and razor in your views happens before the HTTP response. So once the response is sent to the client, all your #Model.value or #if(something) { #Html.Partial(...) } statements will have already translated into pure HTML.
Something you can do to get values from a partial view to your main view is use jQuery:
Imagine a main view like:
#Html.HiddenFor(m=>m.ChosenName, new { id="hiddenGlobalName" }
and a partial view like this:
<input type="text" id="partialNameField" />
<input type="button" value="Save and close popup" id="closeButton" />
<script>
$(function(){
$('#closeButton').click(function(){
var partialValue = $('#partialNameField').val(); // get the value
$('#hiddenGlobalName').val(partialValue); // "save" to main view
});
});
</script>
Because the DOM will be constructed after the HTTP request is over, you have access to all elements of a main view from any included partial view at the time the user sees them.
Hope this can help you!

How to write value to html field from asp.net code behind

I have made an application in javascript using HTML fields in asp.net, as asp text boxes were disturbing the ids, so i used html fields, which are working fine with javascript, now i want to fetch database table columns on page load, and want to assign to html fields, what is the best way to do so? Help me!!!!
You could go back to using the ASP TextBoxes and access the ids in JavaScript as follows:
<%= IDofTextBox.ClientID %>
It's probably the easiest as naturally they can then be accessed in the code behind very easily.
you can use asp text boxes fine if you grab a reference in your javascript to their asp.net generated ID via <%= textboxname.ClientId %>
This is not the right way to do it (I wouldn't recommending it), but if its what you need, then it will work.
Add method="post" action="<your path here>" to your form element and when the submit button posts, you will be able to access all the form variables like so:
string txtName = Request["TextBox1"] ?? string.Empty; //replace textbox 1 with text box name
Just be sure to replace the action in form to your page etc..
But really, going back to <asp:TextBox... will save you a lot more time and as Ian suggested, you can access them with javascript by the server tags <%= TextBox1.ClientId %>
ps: also, the ?? is a null coalesce character. its a short form of saying
if(Request["textbox1"] != null)
txtName = Request["textbox1"];
else
txtName = "";
If I understand you correctly. You just need to add runat="server" and id="someName" to the html fields and access them in the code behind by its given id.

How do I submit disabled input in ASP.NET MVC?

How do I submit disabled input in ASP.NET MVC?
Can't you make the field readonly="readonly" instead of disabled="disabled"? A readonly field value will be submitted to the server while still being non-editable by the user. A SELECT tag is an exception though.
Thanks to everyone:
The way i resolved this:
document.getElementById("Costo").readOnly = true;
document.getElementById("Costo").style.color = "#c0c0c0";
Note:
I got this information on the answer but i got editted.
#ppumkin mentioned this on his comment on this answer but I wanted to highlight it as I was unable to find other resources on submitting data from a disabled <select>. I also believe it is relevant to the question as selects are not <input>s but they are "input"s.
Just include a Hidden field for the disabled select and its all sorted.
Example:
#Html.DropDownListFor(model => model.SelectedID, ... , new { disabled = "disabled"}) #* Won't be posted back *#
#Html.HiddenFor(model => model.SelectedID) #* Will be posted back *#
Caution: this will put two tags on the page with the same ID, which is not really valid HTML and could cause headaches with javascript. For me, I have javascript to set the value of the dropdown by its html id, and if you put the hidden field first, the javascript will find that instead of the select.
Typically, if I have a field that is "read-only" but needs to be submitted back to the server, I will make the display disabled (or simply text), but then add a hidden field with the same name. You still need to make sure that the field is not actually modified on the server-side -- just don't update it from the model in your action -- but the model state will still be accurate if there are errors.
You can also use code like this before the form submits:
$(":disabled", $('#frmMain')).removeAttr("disabled");
By design browsers do not support that.
Either make them readonly which allows submitting values to server
or if you're dealing with controls that are still usable with readonly attribute such as Select, add css style pointer-events: none; to make them non-interactive
Kind of a hack, but works! It also works when you are submitting form directly with submit button without using javascript. No extra work required!
Eg:
<select asp-for="TypeId"
asp-items="#(new SelectList(await TypeRepository.FetchTypesAsync(), "TypeId", "Name"))"
class="form-control form-control-sm"
readonly
style="pointer-events: none;">
</select>
You can create an editor template like the one below
CSS
.disabled {
background-color:lightgray;
}
Editor Template
#model string
#Html.TextBoxFor(x => x,new {#class="disabled", #readonly=true })
This will help in submit model values in ASP.net:
$("#iD").attr("style", "pointer-events: none;background-color:rgb(220,220,220)");
when we are dealing with disabled but checked checkboxes and we want to post the value, we need to ensure our hidden field appears before the #Html.CheckBoxFor hidden field.
following is the link from where I found the answer.
http://davecallan.com/posting-disabled-checkboxes-mvc-razor-views/#comment-11033
I usually use this way for CheckBox or CheckBoxFor because making it disabled is causing the losing the value. Readonly doesn't work on checkbox neither.
#Html.DisplayFor(m => m.Order.Transfer)
#Html.HiddenFor(m => m.Order.Transfer)
expanding Tasos' (":disabled", $('#xxxForm')).removeAttr("disabled"); you can use:
$("#xxxForm").submit(function (e) {
e.preventDefault();
var form = this;
$('#Field1')[0].disabled = false;
$('#Field2')[0].disabled = false;
...
$('#FieldN')[0].disabled = false;
form.submit(); // submit bypassing the jQuery bound event
});
Just put this script in #section scripts in your page.
this will enable inputs when you submit the page, and you should redirect user to another page after submit.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js">
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
Just make that property [Required] in the ViewModel linked to that view.

Categories