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();
});
Related
public ActionResult Edit(int? id)
{
ViewBag.Role = new SelectList((from t in db.Roles where t.RoleID != 1 && t.RoleID != 2 select t), "RoleID", "RoleName");
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
The ViewBag.Role is to generate all the Roles Value into the multiselect checkbox.
<div class="form-group">
#Html.Label("Roles", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Role", null, htmlAttributes: new { #multiple = "multiple", #class = "form-control" })
</div>
</div>
<script type="text/javascript">
$(function () {
$('#Role').multiselect({
includeSelectAllOption: true
});
});
Basically the MultiSelect CheckBox look like the following image.
Here is my question, how do i precheck the roles that the user already have ??
For example, x user have a role Manager so during edit page Manager checkbox will be checked.
You can do it like this:
$('select').multiselect({includeSelectAllOption: true});
// Get your data
var userRoles="1,3"; // You can use a ViewBag like ViewBag.UserRoles for roles of user
// Split data by ","
var userRolesArray=userRoles.split(",");
// Set dataArray
$("select").val(userRolesArray);
// Refresh for cheking default values
$("select").multiselect("refresh");
You can use a ViewBag like ViewBag.UserRoles for roles of user and fill it in your Action.
Online demo (jsfiddle)
i have one form and one uploader (i use PLUploader) and want user fill textboxs and select image in PLUploader and when click on submit button , i pass image and textboxs value to one action , i write this code, but alwaye i get null in textboxs value but get image in action ,i think this problem related to call the one action with form and PLuploader,
public ActionResult Insert(News news, HttpPostedFileBase file)
{
// i get null in new but get file in HttpPostedFileBase
int result = 0;
HttpPostedFileBase FileData = Request.Files[0];
string fileName = null;
fileName = Path.GetFileName(FileData.FileName);
if (ModelState.IsValid)
{
//do some thing
}
else
{
return View(news);
}
}
#using (Html.BeginForm("Insert", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsTitle)
#Html.TextBoxFor(model => model.NewsTitle, new { #class = "form-control",#name="title" })
#Html.ValidationMessageFor(model => model.NewsTitle)
</div>
<div class="col-xs-12">
<div id="uploader" class="img-plc">
<p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
</div>
<ul id="gallery"></ul>
</div>
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsText, new { #class = "text-right" })
#Html.ValidationMessageFor(model => model.NewsText)
#Html.TextAreaFor(model => model.NewsText, new { #rows = "10", #cols = "80", #class = "text-editor", #name = "title" })
</div>
<button type="submit">Submit</button>
}
var uploader = $("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,gears,flash,silverlight,browserplus,html4',
url: '#Url.Action("Insert", "News")',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
multi_selection: false,
multiple_queues: false,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,png" }
],
// Flash settings
flash_swf_url: '/Scripts/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/Scripts/Moxie.xap'
})
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
how i can fixed this ?
i want get news and file in this action
thank you
you're not submitting your whole form; instead you're capturing the submit action with the jQuery event handler for onSubmit:
$('form').submit(function (e) { ... });
If you want to do it this way, you'll have to serialize your News model inside this jQuery code block as well and post it along with the file upload.
I would just stick the HttpPostedFileBase inside the News model and use the normal form submit though.
I have one form and one uploader (I use PLUploader) and want user fill textboxs and select image in PLUploader and when click on submit button,
I pass image and textboxs value to one action, I write this code, but always I get null in textboxs value but get image in action.
I think this problem related to call the one action with form and PLuploader.
public ActionResult Insert(News news, HttpPostedFileBase file)
{
// I get null in new but get file in HttpPostedFileBase
int result = 0;
HttpPostedFileBase FileData = Request.Files[0];
string fileName = null;
fileName = Path.GetFileName(FileData.FileName);
if (ModelState.IsValid)
{
//do some thing
}
else
{
return View(news);
}
}
#using (Html.BeginForm("Insert", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsTitle)
#Html.TextBoxFor(model => model.NewsTitle, new { #class = "form-control",#name="title" })
#Html.ValidationMessageFor(model => model.NewsTitle)
</div>
<div class="col-xs-12">
<div id="uploader" class="img-plc">
<p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
</div>
<ul id="gallery"></ul>
</div>
<div class="col-xs-12">
#Html.LabelFor(model => model.NewsText, new { #class = "text-right" })
#Html.ValidationMessageFor(model => model.NewsText)
#Html.TextAreaFor(model => model.NewsText, new { #rows = "10", #cols = "80", #class = "text-editor", #name = "title" })
</div>
<button type="submit">Submit</button>
}
var uploader = $("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,gears,flash,silverlight,browserplus,html4',
url: '#Url.Action("Insert", "News")',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
multi_selection: false,
multiple_queues: false,
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,png" }
],
// Flash settings
flash_swf_url: '/Scripts/Moxie.swf',
// Silverlight settings
silverlight_xap_url: '/Scripts/Moxie.xap'
})
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
How can I fix this? I want to get news and file in this action.
Create a ViewModel to contain both properties
public class NewsViewModel {
public News News { get; set; }
public HttpPostedFileBase File { get; set; }
}
public ActionResult Insert(NewsViewModel model) {
/* ... */
}
When you create the view pass the ViewModel into the view. Make sure you use the right name for the input field to make it bind correctly:
#Html.TextBoxFor(model => model.File, new { type = "file" })
I would assume you might have to tell your script what name the file input shoul have.
I have got a model as below -
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Password and Confirm Password have to be the same")]
public string ConfirmPassword { get; set; }
In my HTML, I am adding the code as
<label>Password</label>
<span class="req">*</span>
#Html.PasswordFor(x => x.Password, new { #class = "form-control form-control2", #required = "required" })
<p class="signuppace"></p>
<label>Confirm Password</label>
<span class="req">*</span>
#Html.PasswordFor(x => x.ConfirmPassword, new { #class = "form-control form-control2", #required = "required" })
The message for the required field gets displayed but here the ErrorMessage "Password and Confirm Password have to be the same" doesn't get displayed. I have already referred this 1,2 SO links. What am I doing wrong? Any help would be appreciated.
The don't think that the helper adds markup to display a validation error automatically, other than for client side validation using unobtrusive client validation which executes using JavaScript (Not server side).
You want to use #Html.ValidationMessageFor(x => x.ConfirmPassword) to show the error message or simply check for the error using the ModelState.
#if (ModelState.Errors["ConfirmPassword"] != null && !string.IsNullOrWhiteSpace(ModelState.Errors["ConfirmPassword"][0]))
{
// Display the first error message for this field
ModelState.Errors["ConfirmPassword"][0]
}
You don't show all relevant cshtml, but you need to display the validation message.
Either use #Html.ValidationSummary(excludePropertyErrors: false) to display all validation errors in one place, or put #Html.ValidationMessageFor(x => x.Password) near your input field.
I want to make an editing function where you can add metafields (= specific fields for a category) to a category.
What I want to do in the view is
foreach (App.Models.Metafield field in Model.Category.Metafields)
{
<div class="field">
#Html.TextBoxFor(model => field.Name, new { #class = "form-control title" })
#Html.DropDownListFor(model => field.Type, Model.MetaTypes, new { #class = "form-control type" })
</div>
}
The problem is that the Metafields are not added to the viewModel when I hit the save button. So I guess the field.Name and field.Type should be replaced by something else..
This can't work this way because the sent form can't contain these dynamically generated fields with the same name.
However, you can collect the data from these dynamic fields using js and serialize it into a hidden field just before submitting the form, then you can parse it in your server side.
Here is an example with jquery:
$('#save-btn').click(function(e) {
$hidden = $("#hidden");
$hidden.val(getDynamicData());
});
function getDyanmicData() {
var data;
$fields = $(".field");
// get children and calculate data
return data;
}
This may be a bit too 'manual work', but I find it useful to know what's happening. For other solutions you can search form dynamic forms in ASP.NET MVC.
Please try this code
#for(int i=0;i<=Model.Category.Metafields.count();i++)
{
<div class="field">
#Html.TextBoxFor(m=> m[i].Name, new { #class = "form-control title" })
#Html.DropDownListFor(m=> m[i].Type, Model.MetaTypes, new { #class = "form-control type" })
</div>
}