mvc dropdownlistfor validation run before submitting - javascript

I have an MVC 5 Application. I have a View that inherits from a Model View. I have a DropDownlistFor with Validation that cannot be empty.
The problem I have is that Validation executes as soon as I select an item from Dropdownlist. When I select the same First item "Choose a Country", I mean, y select the same default option, validation execute and show a Message "Country is required"...
I put an alert on jquery Submit button and on Controller Method and it does not reach that point.
Another curious thing is that this App is a Migration from Entity Framework to Enterprise Library Store Procedure ..
The Model that inherits the View is loaded on the Controller from Store Procedure instead of EntityFrawork.
This should be transparent to the View. But this error happens only in this versiĆ³n. It Works fine with Entity Framework.
Here is part of the code..
#model AvivaVozSP.Models.UserViewModel
#using System.Web.Mvc.Ajax
<form action="#Url.Action("Create", "Users")" id="form" enctype="multipart/form-data" method="post">
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries, new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
<div class="DvCampoUp">
#Html.ValidationMessageFor(model => model.user.Country_id, "", new { #class = "text-danger" })
</div>
</form>
<script language="javascript" type="text/javascript">
$('form').submit(function (event) {
alert(1);
});
Any Ideas?

Use the default value like this
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries,"Choose a Country", new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
and remove Choose a Country from the list

Related

Combo Box selected value to javascript

In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});

Value from JQuery populated field not binding to MVC model

I'm working on a project with ASP.NET MVC, using Razor. Once the form finishes loading on the page, I expect the user triggers .on ('change') in an input. Once this happens, an AJAX call is executed, returning the user's data, disabling and filling the inputs that are linked to the properties of a model that starts empty (when the page is loaded).
The data is filling up without problems, but when I send it back to the controller to be processed, the values that correspond to the inputs that were filled after the AJAX execution arrive as null.
<div class="form-label-group col-md-4 mb-3">
#Html.LabelFor(model => model.AttendeeName, new { #class = "upside-label", #for = "firstName" })
#Html.EditorFor(model => model.AttendeeName, new { htmlAttributes = new { #class = "form-control", #id = "firstName", #placeholder = Resources.ResourcesPerson.PlaceholderPersonName } })
#Html.LabelFor(model => model.AttendeeName, new { #class = "downside-label", #for = "firstName" })
<div class="text-danger">
#Html.ValidationMessageFor(model => model.AttendeeName)
</div>
</div>
I have tried the following without success:
$("input[name=AttendeeName]").attr('disabled', true);
$("input[name=AttendeeName]").val(data.AttendeeName).change()
Thank you for your assistance.
This is expected behaviour. disabled elements are not sent in form data.
If you still want those values to be sent, don't disable the fields. Possibly try readonly instead, assuming that you don't want users to edit the fields:
$('input[name="AttendeeName"]').prop('readonly', true);

MVC #Html.DropDownListFor change displayed value in javascript

Using MVC 4, I am trying to change the displayed value in the view for #Html.DropDownListFor, based on the action of another drop down list. In the below example, when the user selects any value in the state list, I want the #Html.DropDownListFor to display the indexed 203 value which is US. How to do this?
//in the controller
ViewBag.statelist = new SelectList(db.states, "state_abbr", "state_name");
ViewBag.countrylist = new SelectList(db.countries, "country_id", "country_name", -1);
//in the View
<div class="form-group">
#Html.LabelFor(model => model.states)
#Html.DropDownList("ddlstate", ViewBag.statelist as SelectList, Model.rrq_sec1_waddr_stprov, htmlAttributes: new { #onchange="StateChange()" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.country)
#Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { #id="ddlcountry" })
</div>
//javascript
function StateChange() {
var state = document.getElementById("ddlstate").value;
$("#ddlcountry").val = 203;
};
How do I get the #ddlcountry index=203 which is "US" show up in view then the state drop down changes?
This might help u to select value in second dropdown, onchange event of first dropdown using this jQuery function.
$('#ddlstate').change(function () {
$("#ddlcountry").val( $('#ddlstate').val());
});

Model is null in Kendo UI MVC in Microsoft Edge and Internet Explorer

I am using jquery serializeObject to retrieve model binded textbox and dropdown values in my project. In chrome i get the value for both textbox and dropdown however in Microsoft Edge i am not getting any values for the model binded object. In the bottom code, the value of viewModel comes as null for both SupplierName and SelectedSearchType when I use Microsoft Edge however i get the entered value in Chrome.
Any clue why i am not getting any value in Microsoft Edge and IE?
<form id="formSupplierInvitation" class="form-horizontal">
<fieldset id="SupplierInvitation">
<p style="margin-bottom: 15px;">
<b>Please enter your search criteria: </b>
</p>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.SupplierName, new { #class = "col-sm-4 control-label" })
<div class="col-sm-8">
#Html.TextBoxFor(model => model.SupplierName, new { #class = "form-control", maxlength = 100, #data_toggle = "tooltip", #title = "Maximum length is 100", })
#Html.ValidationMessageFor(model => model.SupplierName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group required">
#Html.Label("Search Type", new { #class = "col-md-3 col-sm-4 control-label" })
<div class="col-sm-8">
#Html.DropDownListFor(m => m.SelectedSearchType, new SelectList(Model.AllSearchTypeLists, "SearchTypeValue", "SearchTypeText"), new { #name = "DropDownSearchType", #class = "form-control", data_placeholder = "Choose Search Type..." })
</div>
</div>
</div>
</div>
<input id="btnSearch" type="submit" value="Search" class="btn btn-default" />
<div class="col-sm-12">
#(Html.Kendo().Grid<SupplierPortal.ViewModels.SupplierInvitationResponseViewModel>()
.Name("GridSupplierInvitation")
.Columns(columns =>
{
columns.Bound(e => e.SupplierNumber).Width("160px");
columns.Bound(e => e.SupplierName).Width("180px");
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.ServerOperation(false)
.Read(read => read.Action("GetSuppliers", "Admin").Data("GetSearchParameters")))
)
</div>
</fieldset>
</form>
<script type="text/javascript">
function GetSearchParameters() {
return {
viewModel: $("#SupplierInvitation").serializeObject()
};
}
$('#btnSearch').click(function (e) {
e.preventDefault();
$('#GridSupplierInvitation').data('kendoGrid').dataSource.read();
});
</script>
public JsonResult GetSuppliers([DataSourceRequest] DataSourceRequest dataRequest, SupplierInvitationRequestViewModel viewModel)
{
var responseViewModels = new List<SupplierInvitationResponseViewModel>();
string supplierName = viewModel.SupplierName;
string selectedSearchType = viewModel.SelectedSearchType;
return Json(responseViewModels.ToDataSourceResult(dataRequest));
}
Update #1: Followed this post and found this fix. I needed to add 'input' attribute.
Jquery Serialize not working only on IE
function GetSearchParameters() {
return {
viewModel: $("#SupplierInvitation input").serializeObject()
};
}
Update #2: Need to update on my previous update. The previous solution adding 'input' only works for input attributes. (obviousuly). If you have a dropdownlist like above which will get converted to 'select' html attribute, you won't be able to get the value for your dropdown. I believe you can go two ways(?) to solve this. First, read the values by their id, set the values in variable and send those values as individual parameters. e.g.
var supplierName = $("#SupplierName").val();
var selectedSearchType = $("#SelectedSearchType option:selected").val();
Secondly, use serializeObject and set the properties values in the serialized object.
var supplierName = $("#SupplierName").val();
var selectedSearchType = $("#SelectedSearchType option:selected").val();
var supplierInvitationObject = $('#SupplierInvitation').serializeObject();
supplierInvitationObject.SupplierName = supplierName;
supplierInvitationObject.SelectedSearchType = selectedSearchType;
There appears to be an interop issue between Microsoft Edge and other browsers when you attempt to serialize from the fieldset. I've authored a short test to help track future support:
var serialized = $('<fieldset><input name="a" value="b"></fieldset>').serialize();
document.body.textContent = ( "a=b" == serialized ? "pass" : "fail" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have filed an issue for the Microsoft Edge team to investigate the matter further. I'll also be working through the internals of this method to more closely identify the point at which Edge deviates from expectations. I will update this answer when I have additional details.

How to get selected value of dropdown when using partial view in mvc?

I am using partial view to display a view inside another and the partial view has the drodown so how to get the value of that dropdown actually i want to display another dropdown based on the value of the first dropdown here is my code in detail:
partial view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<link href="~/Content/control.css" rel="stylesheet" />
<fieldset>
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.CompanyID , new {#class="lbldis"})
</div>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.CompanyID, new SelectList(ViewBag.CompanyList as System.Collections.IEnumerable, "_CompanyID", "Company"), "- Select -",new { #class = "txtbox",id="ddln" })
#Html.ValidationMessageFor(model => model.CompanyID)
</div>
<br />
<div>
#Html.DropDownListFor(Model => Model.ClientID, new SelectList(ViewBag.ClientList as System.Collections.IEnumerable, "_ClientID", "Company"), "- Select -",new { #class = "txtbox" })
#Html.ValidationMessageFor(model => model.ClientID)
</div>
</fieldset>
}
and the view where i am calling this partial view:and the name of that view is Index:
<div id="tab-1">
#Html.Partial("~/Views/PartialViews/_company.cshtml")
</div>
All the dropdowns are working fine and getting the values and all but only problem is with the javascript. Please help me on where to write the javascript i.e in partial view or in Index where I am calling my partial view and how to to display another dropdown based on the value of the first one.
What I have tried so far is below:
<script type="text/javascript">
$("#ddln").change(function onchange(dropdown) {
var myindex = dropdown.selectedIndex;
var SelValue = dropdown.options[myindex].value;
if (SelValue == 'Client3')
{
var see = document.getElementById("ddln");
see.style.display = "";
}
})
</script>
If you are using jquery you can handle controls of partial view from main view using on() function. Earlier (before 1.9) you could have used live() but this has been deprecated since.
$(document).ready(function () {
$('body').on("change", "#ddln", function (evt) {
if ($(this).val() != 'val1') //assume if val1 is the value against which we wish to show.
{
$('#ndl').show();
}
else
{
$('#ndl').hide();
}
});
});
To hide or display the 2nd dropdown based on a value in the first:
var clients = $('#ClientID');
$('#CompanyID').change(function() {
var id = $(this).val();
if (id == 'Client3') { // assume you want to hide it if the selected option value is 'Client3'
clients.hide();
} else {
clients.show();
}
});
Edit
Based on OP's last edit which changed the default id attribute from id="Company" to id="ddln", the code would be modified to
$('#ddln').change(function() { ...

Categories

Resources