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");
}
});
});
Related
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!
I have a DropDownList which has a Car models
#Html.DropDownList("Cars", (IEnumerable<SelectListItem>)ViewBag.Cars, "Select a Value", htmlAttributes: new { #class = "form-control" })
i need the user must select a value also if he select a specific value send the id of the value to url to the action as a parameter
Modify Registration
Cancel Registration
You will need to use javascript to achieve this. So for example you could give your anchor an unique id:
<a id="editRegistration" href="#Url.Action("Edit", "Registration", new { id = "initial value from the database" })" class="text-white">Modify Registration</a>
and then subscribe to the change event of the dropdown and update the href of the anchor:
<script>
$('#Cars').change(function() {
var url = "#Url.Action("Edit", "Registration", new { id = "#ID#" })";
// replace the #ID# placeholder with the selected value
var newHref = url.replace('#ID#', this.value);
$('#editRegistration').attr('href', newHref);
// do the same with the other anchor
});
</script>
I need a help.
I have a User registration form and I have to map "Customer" with user.
Now I want to validate user "customer" which is came from another source and I put the "customer" in Select list "customer" are more then 2000 that's why I use JQuery Chosen plugin to search in select list
but "customer" Field depend on "roles" that's why on page load "customer" field is hidden by default when I change the role "customer" field(chosen select list) display and when i am Selecting customer its not firing remote validation.
I tried to make it visible on "inspect element" and I change the display:none to display:bock and try to change value from chosen its not working when i change the orignal select list value from clicking on select list then its working fine i mean its firing my remote validator method here is full code example what i am doing.
please help i want to validate on when chosen select list value change.
This is RegisterViewModel
public class RegisterViewModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
//for edit view model additionalFields which will only require for edit mode
//[System.Web.Mvc.Remote("DoesCustomerCodeExist", "Account", AdditionalFields = "OldCustomerCode")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Customer Code is required.")]
[Display(Name = "Customer Code", Description = "A customer code come from our oracle system.")]
[System.Web.Mvc.Remote("DoesCustomerCodeExist", "Account")]
[Range(0, int.MaxValue, ErrorMessage = "Please enter valid Customer Code in number only.")]
public string CustomerCode { get; set; }
}
Here is my view cshtml in this file also have js code to display customers chosen Select list when role changed.
//select Role
<div class="form-group">
#Html.LabelFor(m => m.Role, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.Role, ViewBag.Roles as SelectList,"", new { #class = "form-control chosen-select", data_placeholder = "Select a Role" })
#Html.ValidationMessageFor(m => m.Role, "", new { #class = "text-danger" })
</div>
</div>
//Customer Code
<div class="form-group condition-div user hidden ">
//this hidden field is only for edit mode
//#Html.Hidden("OldCustomerCode", Model.CustomerCode)
#Html.LabelFor(m => m.CustomerCode, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.CustomerCode, (SelectList)ViewBag.Customers, "", new { #class = "form-control chosen-customers", data_placeholder = "Select Customer" })
#Html.ValidationMessageFor(m => m.CustomerCode, "", new { #class = "text-danger" })
</div>
</div>
#section Styles{
#Styles.Render("~/Content/chosen")
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/chosen")
<script type="text/javascript">
$('input[type=text]').tooltip(
{
placement: "right",
trigger: "focus"
}
);
$(".chosen-select").chosen({ allow_single_deselect: true});
$('#Role').change(function () {
if (this.value == "") {
$('.condition-div').addClass('hidden'); // hide all the conidional divs
} else if (this.value == "NBP User" || this.value == "NBP Head" ) {
$('.condition-div.admin').addClass('hidden'); /// hide admin conditional divs
$('.condition-div.user').removeClass('hidden'); // show user role conditioanl div
//configure selectlist to Chosen select and if i remove this line and show orignal select list its working fine mean remote validating on change but if i use this is not working on change.
$(".chosen-customers").chosen({ allow_single_deselect: true, search_contains: true });
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-customers)" });
} else if (this.value == "ICIL User" || this.value == "ICIL Head" || this.value == "FIO User" ) {
$('.condition-div.user').addClass('hidden'); /// hide user role conditional divs
$('.condition-div.admin').removeClass('hidden'); // show admin role conditional divs
$(".chosen-branch").chosen({ allow_single_deselect: true });
$.validator.setDefaults();
}
});
</script>
}
Controller Action to validate Customer Code
public ActionResult DoesCustomerCodeExist(string CustomerCode, string OldCustomerCode)
{
//the oldCustomerCode will come null in this case cause its register view and in edit view OldCustomerCode will be use
if (CustomerCode == OldCustomerCode)
return Json(true, JsonRequestBehavior.AllowGet);
if (DbContext.Users.Any(x => x.CustomerCode == CustomerCode))
return Json("Customer code already exists in application. Please verify user details.", JsonRequestBehavior.AllowGet);
if (DbOracle.IsCustomerCodeExist(CustomerCode))
return Json(true, JsonRequestBehavior.AllowGet);
else
return Json("The customer code does not exist in database.", JsonRequestBehavior.AllowGet);
}
All code working fine if i did not use jquery chosen plugin.
In short issue is when I use chosen plugin for select list remote validation is stop validating values.
I can share images if u guys need now I have a limited account so i cant upload snaps shots....
Please help me.
you should have to put some JQuery on client side to track the "CustomerCode" field when change of customer field jsut call "focusout()" event of "CustomerCode" e.g:
$('#CustomerCode').change(function () {
$(this).focusout();
});
I have one MVC project,containing user registration form which have 25-30 fields to fill. After filling form if user forgot to fill mandatory field then it will shows validation error. But remaining all fields loss their data.
I mentioned in controller like
if (!ModelState.IsValid)
{
ModelToDBclass obj = new ModelToDBclass();
objModel.Id = Convert.ToInt32(obj.GetMaxPaperId());
objModel.countryNameDB = obj.GetcountryName();
return View(objModel);
}
and finally it returns the blank view. but at runtime when it comes to
return View(objModel); , the model shows the data with every field, but when it comes to view it unable to show record in text boxes and dropdown. I used textbox like,
<div class="col-sm-2"><input type="text" class="form-control" name="ConsumerFName" id="txtConsumerFirstName" placeholder="First Name" />
#Html.ValidationMessageFor(m => m.ConsumerFName)</div>
so, please help me how can i display filled record after validation error
You should always use Html Helper
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" }, placeholder = "First Name", autofocus = "autofocus" })
Then only when the Model state is not valid, it will show the returned object values at the respective fields. Don't normal html tags.
Hope this helps
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"})