I am passing a variable ViewBag.crimeRef from my controller and am using it to display a message which works fine:
#if(ViewBag.crimeRef != null)
{
<div class="alert alert-dismissable alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
Sorry, there are no matching results for the crime reference <strong>#ViewBag.crimeRef</strong>. Please try searching again.
</div>
}
I figured I could use the same methodology to populate the input's value too, however I'm getting a CS1002: ; expected error:
<input type="text" class="form-control" maxlength="11" id="crimeRef" name="crimeRef" placeholder="Crime reference"
#if(ViewBag.crimeRef != null) { value="#ViewBag.crimeRef" }>
Is there anyway I can populate the input's value using the ViewBag variable?
Many thanks
Answer 1 :-
<input type="text" class="form-control" maxlength="11" id="crimeRef"
name="crimeRef" placeholder="Crime reference"
value="#(ViewBag.crimeRef ?? String.Empty)" >
Answer 2 :-
I m including Nick's answer here because this is the accepted answer, so it will help other stackoverflow users to get answer of their question at one place.
Conditional statements are actually built into Razor as of MVC4 :
Conditional HTML Attributes using Razor MVC3
So simply using this:
<input type="text" class="form-control" maxlength="11" id="crimeRef" name="crimeRef" placeholder="Crime reference"
value="#(ViewBag.crimeRef)">
Will only render the value attribute if ViewBag.crimeRef isn't null - perfect!
Conditional statements are actually built into Razor as of MVC4: Conditional HTML Attributes using Razor MVC3
So simply using this:
<input type="text" class="form-control" maxlength="11" id="crimeRef" name="crimeRef" placeholder="Crime reference"
value="#(ViewBag.crimeRef)" }>
Will only render the value attribute if ViewBag.crimeRef isn't null - perfect!
Thanks to Andrei for the pointer!
The way you are currently trying to do this won't work, value isn't a server-side variable therefore you can't reference it like you are. You can, however, do something a lot simpler
value='#(ViewBag.crimeRef ?? "")'
Remove #ViewBag.crimeRef from quote and try this
<input type="text" class="form-control" maxlength="11" id="crimeRef" name="crimeRef" placeholder="Crime reference" value=#(String.IsNullOrEmpty(ViewBag.crimeRef)?ViewBag.crimeRef:String.Empty) />
<input type="text" class="form-control" maxlength="11" id="crimeRef" value="#((ViewBag.crimeRef==null)?0:ViewBag.crimeRef)" name="crimeRef" placeholder="Crime reference">
In Controller action
ViewBag.crimeRef = null; or ViewBag.crimeRef = 1;
Related
ASP.NET MVC Core if that makes any difference
Is there a simple way to disable some field validators in a model or view under certain cases?
Most information on the web looks to be from the ASP.NET Forms era.
I could not find too many things to try out but, this looks to not do the trick.
<label asp-for="Files.PromoImage" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Files.PromoImage" class="form-control" />
#if (Model.Content.NewArticle)
{
<span asp-validation-for="Files.PromoImage" class="text-danger"></span>
}
</div>
<div class="col-md-8">
<div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
</div>
<input asp-for="Files.PromoImage"/> will generate validation span and data-required attribute if the PromoImage property is marked with the [Required] attribute. You can check the generated html in the browser.
The easiest way to achieve what you want is to remove the [Required] attribute in the model and have something like this in the view:
#if (Model.Content.NewArticle)
{
<input class="form-control" data-val="true"
data-val-required="The PromoImage field is required." name="Files.PromoImage"
placeholder="Promo Image" type="text" value="">
}
else
{
<input asp-for="Files.PromoImage" class="form-control"/>
}
Then again on the server, in your post action method, you have to do a manual validation for the PromoImage property.
Not so trivial but more elegant approach is to extend the MVC and jQuery validation with your own validation attribute and jQuery validator, e.g. [RequiredIf]. The API is slightly different in ASP.NET Core 1.0, but here is an example: Custom validation
I need to take the username, email and password a user enters in an html form (in index.aspx) and use it in an asp.net code in another page (register.aspx in a folder called 'u').
This is the form:
<form action="u/register.aspx" method="post" id="regForm">
<input type="text" name="fname" id="fname" placeholder="Full Name (Optional)" maxlength="16" />
<input type="text" name="uname" id="uname" placeholder="Username" maxlength="16" />
<input type="email" name="email" id="email" placeholder="Email Address" maxlength="32" />
<input type="password" name="pwd" id="pwd" placeholder="Password" maxlength="16" />
<input type="password" name="repwd" id="repwd" placeholder="Repeat Password" maxlength="16" />
<input type="submit" value="Sign Up" id="signup" />
</form>
But, when I'm using Request.QueryString["fname"] for example, it doesn't take 'fname' from the form, it just takes a null.
What can I do to solve this? Is there a different method I can use to achieve the wanted result?
Thanks a lot!
You are doing it wrong.
Request.QueryString contains information related to data added after ? in the URL (ex. http://www.contoso.com?mydata=1¶m2=yy).
You have to use Request.Form to access "POST" data.
QueryString will only give the parameters on the query string of the url check here.
If you want all the parameters you will need to use the Params property.
As others have already said Request.QueryString contains data after the ? in url.
You can use Request.Form or if you want the data as part of the url, you can change your form element method attribute to "get"
I would like to display a form that lets a user enter up to 10 rows of information. If they need to go over, I'm going to use an "add additional row" button that will add one row at a time. What will my Model class look like for something like this? When I use javascript to add a new row, how can I tie that new row into the Model as well?
This article from Phil Haack shows you how to bind to collections. You'll need to use the javascript to create the new row with the correct names.
Probably this rows contains related values, so you can give the same name to all theses inputs in the html, and declare that you action receive an array of values.
Assume that you have this
<form method="post" action="/Controller/YourAction">
<input type="text" name="row" value="1" />
<input type="text" name="row" value="2" />
<input type="text" name="row" value="3" />
<input type="text" name="row" value="4" />
<input type="text" name="row" value="5" />
<input type="text" name="row" value="6" />
<input type="submit" />
</form>
all that you need to do is declare this inside your Controller
public ActionResult YourAction(int[] row)
{
//put your code here
}
and you will have all the values inside the row array
You may take a look at the following blog post which explains how to achieve exactly that. It uses a custom helper (Html.BeginCollectionItem) which allows to use non sequential as collection indexes instead of numbers which makes adding/deleting new items much easier.
All the examples I can find are in Visual Basic, but I am using C#.
I want to get the data that is in a textbox in a form.
My code so far:
<form action="login.aspx" method="get">
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="text" name="password" /></p>
<input type="submit" value="Submit" />
</form>
So what could I do? Because I keep getting told to do this:
Dim UserName
UserName = Request.Form("UserName")
But it doesn't work in C#.
Don't need to do that on asp.net; simply change your markup like so:
<form action="login.aspx" method="post" runat="server">
<p>Username: <input type="text" name="username" runat="server" id="txtUsername" /></p>
<p>Password: <input type="text" name="password" runat="server" id="txtPassword"/></p>
<input type="submit" value="Submit" />
</form>
And on code behind:
string UserName= txtUsername.Value;
And yes, Shawn also caught a good one, you should use POST.
Your method should be POST.
<form action="login.aspx" method="post">
The sample code you posted is vb.net. C# has it's own syntax and keywords.
to get the value you can use the following (not an optimal solution for webforms)
string userName = Request.Form["UserName"];
I would suggest going through some c# tutorials to get a handle on the language. Here's the first one i found http://www.csharp-station.com/Tutorial.aspx
Is it possible to selectively disable the autofill feature in text fields using code?
I'm developing my custom code in ASP.Net AJAX to search for the suggestion in the database and I would like to prevent the browser suggestions from appearing when the user starts typing in the textbox.
I'm looking for a solution that works in the most modern browsers (IE 7 & 8, Firefox, Safari and Chrome). It's is ok if the workaround is in Javascript.
Look at the autocomplete HTML attribute (on form or input tags).
<form [...] autocomplete="off"> [...] </form>
W3C > Autocomplete attribute
Edit:
Nowadays - from the comments - web browsers do not always respect the autocomplete tag defined behavior. This non-respect could be surrounded with a little of JavaScript code but you should think about you want to do before use this.
First, fields will be filled during the page loading and will only be emptied once the page load. Users will question why the field has been emptied.
Second, this will reset other web browser mechanisms, like the autofill of a field when you go back to the previous page.
jQuery( function()
{
$("input[autocomplete=off]").val( "" );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" value="John" autocomplete="off">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" value="qwerty" autocomplete="off">
</div>
<input type="submit" value="Login">
</form>
you can put it into your inputs:
<input type="text" name="off" autocomplete="off">
or in jquery
$(":input").attr("autocomplete","off");
There are 2 solutions for this problem. I have tested following code on Google Chrome v36.
Recent Version of Google Chrome forces Autofill irrespective of the Autocomplete=off.Some of the previous hacks don't work anymore (34+ versions)
Solution 1:
Put following code under under <form ..> tag.
<form id="form1" runat="server" >
<input style="display:none" type="text" name="fakeusernameremembered"/>
<input style="display:none" type="password" name="fakepasswordremembered"/>
...
Read more
Solution 2:
$('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {
var input = this;
var name = $(input).attr('name');
var id = $(input).attr('id');
$(input).removeAttr('name');
$(input).removeAttr('id');
setTimeout(function () {
$(input).attr('name', name);
$(input).attr('id', id);
}, 1);
});
It removes "name" and "id" attributes from elements and assigns them back after 1ms.
Adding an autocomplete=off attribute to the html input element should do that.
Add the AutoCompleteType="Disabled" to your textbox
This should work in every browser
<script type="text/javascript">
var c = document.getElementById("<%=TextBox1.ClientID %>");
c.select =
function (event, ui)
{ this.value = ""; return false; }
</script>
My workaround is to make the password field a normal textbox, then using jquery to turn it into password field on focus:
<asp:TextBox runat="server" ID="txtUsername" />
<asp:TextBox runat="server" ID="txtPassword" />
<script>
$("#txtPassword").focus(function () {
$("#txtPassword").prop('type', 'password');
});
</script>
I have successfully tested this in Edge and Firefox.
<input type="text" id="cc" name="cc" autocomplete="off">
works for regular text input.
For passwords, you need to use autocomplete="new-password"
<input type="password" id="cc1" name="cc" autocomplete="new-password">
per Mozilla Development Network
Place below code above your username control. This will work in call the browser.
<div style="margin-left:-99999px; height:0px;width:0px;">
<input type="text" id="cc" name="cc" autocomplete="off">
<input type="password" id="cc1" name="cc" autocomplete="off">
</div>