MVC/Rzor: textbox should show NO value after postback - c#

In a MVC Form Post scenario, i want to have an empty textbox after the data was posted to the server and the page is again served to the user. Right now, the posted username shows in the the textbox after the postback.
#using (Html.BeginForm("SignIn", "Account", FormMethod.Post))
{
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #type = "email", required = "", pattern = "^", #placeholder = "E-mail", #title = "", #id = "UserName", data_hint = "Required"})
}
At first, the model containing the username was sent back to the form, so i thought that caused it. I now send back a "clean" model with even a forced empty username but that doesnt help either.
return View("SignIn", "_Layout", new ViewModel
{
UserName = ""
});
How do i get an empty textbox after postback?

Use ModelState.Clear() before setting value. When you post a model back to an ActionResult and return the same View, the values for the model objects are contained in the ModelState.
Then return new Model,
ModelState.Clear();
return View("SignIn", "_Layout", new ViewModel());

Use as
#using (Ajax.BeginForm("SignIn", "Account", new AjaxOption{HttpMethod="post", onSuccess="success(data)"))
{
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #type = "email", required = "", pattern = "^", #placeholder = "E-mail", #title = "", #id = "UserName", data_hint = "Required"})
}
<script>
function success(data){
$("#COntrolID").val("");
}

Simply reload the page after success the call
like
window.location.href = '#Url.Action("SignIn", "_Layout")';
This will work for you.

There's something about MVC you should know, which is, how does it handle query strings and invoke validation as well as populate the Viewmodel/model...
Answer: On a postback before the controller gets invoked for that action method MVC attempts to do the validation work. This is why you can use the validation check in the controller before anything else is done!
if(!ModelState.IsValid)
But what happens next is confusing until you understand it. MVC and the browser only deal in Query strings per the HTTP protocol. So in order for MVC to make strong types, it has to first create a null instance of the model or viewmodel, then it will populate any field in that newly created object with values from the postback that have the same names!
If on returning the posted view you are seeing things you did not expect it simply means the BeginForm logic told MVC what property name is coming back and it told it the value. This is the only way a posted value is returned in a view using MVC.
If you don't want that value simply exclude it from the post back.

add
autocomplete="off"
to your textbox
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #type = "email", required = "", pattern = "^", #placeholder = "E-mail", #title = "", #id = "UserName", data_hint = "Required", #autocomplete = "off"})

Related

Binding data from session to drop down list asp.net mvc

In my web application, I have added a dropdownlist for the nav bar.
There I want to load some data from the database.
So in the Home Controller, I have used a view bag option.
ViewBag.MyBranch_Id = new SelectList(BranchList, "Id", "Name");
In this view, I called it as
#Html.DropDownList("MyBranch_Id", null, new { #class = "form-control js-dropdown js-MyBranch", #Id = "Branch" })
But the issue is this dropdown I created on the layout view. So when I navigate to another view, then the view bag data error occurs. (Because when I moved to another controller, the view bag method is on the HomeController Index Action. So then the View bag Data become null.)
So then I load the data to the session. So on the layout page, I called the session data as
#{
List<SelectListItem> MyBranch = Session["MyBranch"] as List<SelectListItem>;
}
and the dropdown menu
#Html.DropDownList(MyBranch, null, new { #class = "form-control js-dropdown js-MyBranch", #Id = "Branch" })
MyBranch has an error . Cannot convert selectListItem to string.
I cant use DropDownListFor because this has no model to assign the session data.
Is there any way of doing this?
Replace Your code in view like below:
SelectList MyBranch = Session["MyBranch"] as SelectList;
#Html.DropDownList("MyBranch", MyBranch, new { #class = "form-control js-dropdown js-MyBranch", #Id = "Branch" })
You should pass MyBranch as selectlist in dropdownlist
I wish that helps!

asp.net mvc set textbox value from value in url without jquery or javascript

I have a textbox inside a form tag like this:
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #type = "email", #aria_describedby = "emailHelp", #text=Request.QueryString["Email"], #value=Request.QueryString["Email"] })
<label>Email</label>
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger", #style = "float:right;" })
Now here is the trick... I have an url that goes like this:
example.com/Registration?Email=someemail#example.com
Now I'm trying to set the value of my textbox automatically by setting the value like this:
#text=Request.QueryString["Email"], #value=Request.QueryString["Email"]
But this doesn't works... The textbox is still empty after the page is loaded...
And I have looked into the html for example and I can see for example text attribute of my input text tag being set to someemail#example.com
What am I doing wrong here?
Okay I found a way to do it. Turns out this is the valid way to do it:
public ActionResult Registration()
{
var regViewModel = new UserRegistrationViewModel { Email = Request.QueryString["Email"] };
return View(regViewModel);
}

Razor: How to dynamically assign a value to a read only TextBox field?

I have a read-only text box which is supposed to be initialized to a value dynamically. This field is present on a page which is used to enter values to details corresponding to the player that was created in the previous page (I am using RedirectToAction() for this purpose, but was unable to access the passed "PlayerID" value from the controller of the current page. So decided on using TempData. ). Since the PlayerID changes each time a new player is added, this field should display that value while still remaining read-only.
Also, this is a 'required' field, so the form cannot be submitted until the value is set.
#Html.TextBoxFor(model => model.PlayerID, htmlAttributes: new { #readonly = "read-only", #class = "control-label col-md-2", value = #Html.Raw(TempData["PlayerID"]) })
How can I set the value of this field as it is in the TempData["PlayerID"]?
You can either have a JavaScript that runs on the page load, ex:
#section Scripts
{
<script>
$(function(){
$("#PlayerID").val('#TempData["PlayerID"]');
});
</script>
}
Or, you can initialize the Model for the view inside the action, so if your action name was 'PlayerDetails', then you should have something like this:
public ActionResult PlayerDetails()
{
return View(new Player{PlayerID=TempData["PlayerID"]}
}
This way, when the view get bound to the view model, it will be initialized to the passed value.
You can try below code:
#Html.TextBox("PlayerID", #TempData["PlayerID"] ,new { #readonly = "read-only", #class = "control-label col-md-2"})
Or in your case:
#Html.TextBoxFor(model => model.PlayerId, htmlAttributes: new { #readonly = "read-only", #class = "control-label col-md-2", Value = #Html.Raw(TempData["PlayerID"]) })

MVC Validation - Server side validation won't allow resubmit using Kendo

Our application (MVC5) has some very complex validation that needs to be done server side (compound capacity checks, workflow validation, and more). The problem we are running into is that once server side validation fails and returns to the same view, the client side never submits values for any fields again (0 for int, empty strings, etc.)
Our general pattern is as follows:
public ActionResult PerformSomeAction()
{
var model = GetActionTemplate();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PerformSomeAction([Bind(Include = ActionTemplate.FIELDS)] ItemTemplate template)
{
string errorMessage;
if (ModelState.IsValid)
{
bool isValid = ValidateAndPerformAction(template, out errorMessage)
if(isValid)
return RedirectToAction("Action", "Controller");
}
// Reset non-bound fields from new template
var model = GetActionTemplate();
template.FieldValue = model.FieldValue
return View(template);
}
Our views don't have anything special in them, other than the fact that some of our editors are built with the Telerik Kendo library. However, the symptoms are seen for all controls, not just Kendo based ones.
A basic View layout for editing a field is as follows:
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.Kendo().TextBoxFor(model => model.Name).HtmlAttributes(new
{
title = ModelMetadata.FromLambdaExpression(model => model.Name, ViewData).Description
})
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
Does anyone have any suggestions on what we are doing wrong?
Note: While it could be argued that this validation could be triggered through AJAX or other service calls, we would prefer to do it with the post implementation that we are using.
Update:
After further research, it appears this has to do with Kendo and not MVC. If I switch my View to be the following:
#Html.EditorFor(model => model.Volume)
Instead of:
#Html.Kendo().NumericTextBoxFor(model => model.Volume).HtmlAttributes(new
{
#class = "",
title = ModelMetadata.FromLambdaExpression(model => model.PreBoilVolume, ViewData).Description
}).Value(Model.Volume)
Everything appears to work fine. So somewhere in that Kendo statement it fails to rebind when returning from the post. It doesn't matter if I set the value again manually, it will never send it back in.
I guess it is time to get rid of some Kendo statements and go back to a more basic UI.
What you "want" to do is a very basic scenario for MVC with failed validation.
The first one that always catches people is with drop down lists. The posted model, does not contain the list of items, so has to be re-populated after failed validation, and then passed back into the view on return.
When I can't solve things like this I start commenting stuff out and work forwards. So in this case strip your model back to one non-ID property and see if it will work. Then you can try and track down the culprit.
It looks like the selectedvalues are not set on the model. Try change these lines of code:
var model = GetActionTemplate();
template.FieldValue = model.FieldValue
return View(template);
to something like this:
var model = GetActionTemplate();
model.Selectedvalues = template.FieldValue ?
return View(model);

hide the default value of a textBoxFor

Note - this is an asp.net MVC 4 application using Razor 2 views...
basically I have a textbox in a view waiting for the user to input data,
this data makes up the values for properties of a model which I want to save to the Db.
The data associated with this textbox has a [required] tab in the Model. I cannot save the model without a value for this textbox as the Model is not valid.
I know I can simply add #Value to the #HtmlTextBoxFor line, put this means that value is displayed to the user.
Is there away to have a default value hidden, so that the user only see's the placeholder text but the "value" will be saved to the Db.
Any ideas...?
textbox..
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "Title"})
controller
if (ModelState.IsValid)
NewsArticle newNews = new NewsArticle();
newNews.Title = newsArticle.Article.Title;
You can add an ID to the textbox as follows:
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "", #id="txtTitle"})
Then call following jquery function on form submit event
$(function(){
$("form").submit(function () {
if($("#txtTitle").val() == ""){
$("#txtTitle").val("Default Value");
}
});
});

Categories