How to pass both the model value and javascript value to controller - javascript

I am submitting the form which has the css dropdownlist for gender how to submit the gender selected value to controller i am getting tht value null
<div class="regi-field-set">
<div id="ddlgender" class='selectBox' tabindex="7">
<span class='selected' id="gender">gender</span>
<span class='selectArrow'>&#9660</span>
<div id="disableasterisk5" style="padding-bottom:8px"><span class="required">*</span></div>
<div class="selectOptions" id="genderSelectOptions">
<span class="selectOption" id="ddlgen">male</span>
<span class="selectOption" id="ddlgen1">female</span>
</div>
</div>
<div class="regi-field-set">
#Html.TextBoxFor(model => model.DOB, new { #class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
<div id="disableasterisk7"><span class="required">*</span></div>
<div class="clear"></div>
#Html.ValidationMessageFor(model => model.DOB)
</div>
how to pass both value to controller all other fields in the form are using html.helper fields only gender field is css implemented
Is there any way to pass the entire model and the gender selected value to controller
please help

If I understood your question, the answer of passing to the View both the "model" and a list of something else to use in a dropdown list can be done by the following code:
Controller
....
var model = service.GetMyThing(id);
var genderList= service.GetGenders().Select(p =>
new SelectListItem { Value = p.Id.ToString(), Text = p.Name }).ToList();
ViewBag.GenderList = genderList;
return View(model);
View
....
#Html.DropDownList("GenderId",(IEnumerable<SelectListItem>)ViewBag.GenderList)
....
<div class="regi-field-set">
#Html.TextBoxFor(model => model.DOB, new { #class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
<div id="disableasterisk7"><span class="required">*</span></div>
<div class="clear"></div>
#Html.ValidationMessageFor(model => model.DOB)
</div>
Note: this is NOT the only solution, custom HTMLHelpers can be used to draw the combo.

using ajax you can achieve this : don't use form & declare your attributes like this in tags:
#Model.idText
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>
jquery:
$(function (e) {
// Insert
$("#btnSubmit").click(function () {
$.ajax({
url: "some url path",
type: 'POST',
data: { textField: $('#textValue').val(), idField: '#Model.idText' },
success: function (result) {
//some code if success
},
error: function () {
//some code if failed
}
});
return false;
});
});
Hopefully it will help you

Related

Get combo box selected value from JavaScript

I'm creating a web form using the bootstrap wizard.
Here I'm stuck within a few operations.
As a first step, I have added a drop-down menu and there in the selected event, I'm taking the selected value from the javascript. That's working fine.
So in the next section, there is another combo box and the selection change event I also want to get the selected value of that combo box and the previously selected combo box value.
So I did this method but it does not return the selected value.
Can you help me with this?. Still, I'm not good with javascript
This is the first combo box.
<div class="form-row center">
<div class="form-holder"> #Html.DropDownListFor(model => model.Language, new SelectList(new[] { "English", "සිංහල", "தமிழ்" }),"Please Select the Language", new { #class = "form-control js-dropdown",Id ="DropLanguage" }) </div>
</div>
This is the second Combo box
<div class="form-holder w-100">
<div class="col-md-12"> #Html.DropDownList("ServiceTypeId", null,language == "Secondary" ? "For which service you came for?" : language == "Primary" ? "ඔබ පැමිණියේ කුමන සේවාව සඳහාද?" : language == "Third" ? "நீங்கள் எந்த சேவைக்காக வந்தீர்கள்" : "", htmlAttributes: new { #class = "form-control", Id = "ServiceType" }) <i class="zmdi zmdi-quote"></i> #Html.ValidationMessageFor(model => model.ServiceTypeId, "", new { #class = "text-danger" }) </div>
</div>
This is the javascript
< script type = "text/javascript" >
$(document).ready(function () {
$("#DropLanguage").on("change", function () {
// This is the jQuery way of finding selected option's text
var myVar = $(this).find("option:selected").text();
// Post the value to your server. You should do some error handling here
$.ajax({
url: '/MainDetails/SetSession',
type: 'POST',
dataType: 'json',
cache: false,
async: false,
data: {
myVariable: myVar
},
success: function (data) {
if (data.Success == true) {
$("#mydiv").load(window.location.href + " #mydiv");
}
}
});
});
$("#ServiceType").on("change", function () {
var ServiceId = document.getElementById("ServiceType");
var Language = document.getElementById("DropLanguage");
alert(ServiceId);
alert(Language);
});
});
<
/script>
Im not getting value on this section $("#ServiceType").on("change", function () {

CLient side validation message does not display when javascript to disable submit button is added

I have a simple form with 2 dropdown fields and a submit button in my MVC application. I have enabled client side validation and it works fine. I have now added a javascript to disable the submit button to prevent the form being submitted twice. For some unknown reason the client validation message does not display when I add this script.
This is my form:
#using (Html.BeginForm("Recycle", "GetList", FormMethod.Post, new { id = "myForm" }))
{
<!-- Server list -->
<div>
<span>Site type: </span>
#Html.DropDownListFor(m => m.uInputS, new List<SelectListItem>
{
new SelectListItem {Text = "text", Value = "value" },
new SelectListItem {Text = "text", Value = "value" }
}, "Select site type")
#Html.ValidationMessageFor(m => m.uInputS, "", new { #class = "error" })
</div>
<!-- Application list -->
<br />
<div>
<span>Application: </span>
#Html.DropDownListFor(m => m.uInputA, new SelectList(string.Empty, "Value"))
#Html.ValidationMessageFor(m => m.uInputA, "", new { #class = "error" })
</div>
<br />
<!-- Submit-->
<div>
<input id="Submit1" type="submit" value="Submit" onclick="return FreezeSubmit();" />
</div>
}
Below is the jquery I used to disable the submit button.
<script>
function FreezeSubmit() {
var s = $("#uInputS").val();
var a = $("#uInputA").val();
if ((s && a)) {
$('#myForm').submit();
$('#Submit1').prop('disabled', true);
return true;
}
else {
$('#Submit1').prop('disabled', false);
return false;
}
}
</script>
This is my Model:
public class GetList
{
[Required(ErrorMessage = "Please select site type")]
public string uInputS { get; set; }
[Required(ErrorMessage = "Please select application name")]
public string uInputA { get; set; }
}
I am very new to programming and I am not able to figure out why the client validation message fails to display because I added some javascript. Any help is appreciated. Thanks!
Remove onclick in
<input id="Submit1" type="submit" value="Submit" onclick="return FreezeSubmit();" />
change to
<input id="Submit1" type="submit" value="Submit" />
and you need change your script to
<script>
$(document).ready(function(){
checkEmpty()
})
$('input').change(function() {
checkEmpty();
});
function checkEmpty(){
var s = $("#uInputS").val();
var a = $("#uInputA").val();
if ((s && a)) {
$('#Submit1').prop('disabled', true);
}
else {
$('#Submit1').prop('disabled', false);
}
}
</script>
disable the button when submit handler is called, see jquery api here
$( "#your_form_id" ).submit(function(event) { // Handler for .submit() called.
$('#Submit1').prop('disabled', true);
});

Hide checkbox/div based on textbox value

I have a dropdown, when i select an item its categoryId is assigned to textbox. Then i Have 2 checkboxes 'IsAnonymous' and 'ShowReport'. I want to implement that is the value in textbox is 1 then both checkbox will be visible and when value will be 2 then 'ShowReport' checkbox must be hidden.
javascript
var ReportDiv = $('#ReportDiv');
$('#cmbCategories').on('change', function () {
if ($(this).val() == '1') {
ReportDiv.hide();
}
else {
ReportDiv.show();
}
});
View
#Html.DropDownListFor(p => p.PollSurveyId, Model.PollSurveyDetails, "Select Poll/Survey", new { #class = "form-control", required = "required", #id= "DDPollName" })
#Html.TextAreaFor(p => p.CategoryID, new {id= "cmbCategories" })
<div class="form-group">
#Html.Label("Is Anonymous")
#Html.CheckBoxFor(p => p.IsAnonymous)
</div>
</div>
<div class="col-lg-3">
<div class="form-group" id="ReportDiv">
#Html.Label("Show Report")
#Html.CheckBoxFor(p => p.ShowReport, new { id= "CBReport" })
</div>
<!-- /.col-lg-6 (nested) -->
</div>
Added a picture to give idea of my page

how to change single selection to multiselect dropdown with checkboxes using asp.net MVC

I am using below code for dropdown
#if (ViewBag.EventContentTypeId == Convert.ToInt32(EventContentType.Events))
{
<div class="col-sm-3 form-group input" style="padding-left:0">
<div class="input-group">
#Html.DropDownList("EventCategoryDDL", #ViewBag.EventCategories as IEnumerable<SelectListItem>, "-- Select Category --", new { #class = "form-control" })
<span class="input-group-addon">
<i class="fa fa-file-text" aria-hidden="true"></i>
</span>
</div>
</div>
}
I want to change these to multi-select dropdown with checkbox.
And this is my controller code and this is in selectlist and I am unable to modify to multiselectlist is there a way to change to multiselectlist of selectlist.
ViewBag.EventCategories = ViewBag.EventContentTypeName == EventContentTypeString.Events.Value ? _commonService.GetEventCategoriesModel().Where(category =>category.OptionText != "Camp Kaufmann").Select(i => new SelectListItem()
{
Text = i.OptionText,
Value = i.OptionValue.ToString()
})
_commonService.GetEventCategoriesModel().Select(i => new SelectListItem()
{
Text = i.OptionText,
Value = i.OptionValue.ToString()
});
And how should I change to multiselectlist in my controller side and also how to bind dropdown with check boxes of multiselect.
You can use bootstrap-multiselect plugin check this link.
Action Methods
public ActionResult Index()
{
List <SelectListItem> vegList = new List<SelectListItem>
{
new SelectListItem {Text = "Cheese",Value="1" },
new SelectListItem {Text = "Mushrooms",Value="2" },
new SelectListItem {Text = "Tomatoes",Value="3" },
new SelectListItem {Text = "Onions",Value="4" }
};
ViewBag.Vegetables = vegList;
return View();
}
[HttpPost]
public ActionResult AddVegetables(string[] VegetablesDDL)
{
var selectedVegetablesIDs = VegetablesDDL.ToList();
foreach(var selected in selectedVegetablesIDs)
{
// use selected item
}
return View();
}
View:
#using (Html.BeginForm("AddVegetables", "Home", FormMethod.Post))
{
#Html.Label("Vegetables:")
<br />
<br />
#Html.DropDownList("VegetablesDDL", #ViewBag.Vegetables as IEnumerable<SelectListItem>, "-- Select Vegetables
--", new { #class = "form-control", multiple = "multiple" })
<br />
<input type="submit" value="Submit" />
}
Script:
<script type="text/javascript">
$(document).ready(function() {
$('#VegetablesDDL').multiselect();
});
</script>
Note:
Add bootstrap-multiselect.css in head section of your page and bootstrap-multiselect.js in bottom of your page.
Also its better to use ViewModels instead of ViewBag check this.
Reference:
1.
2.

jquery autocomplete - string array

My web form model(AdtFormModel) has this variable:
public List<String> TemoinsVille { get; set; }
I use a list because I want the user to be able to dynamically add more 'TemoinsVille' in the form. For now I have two textboxfor, when I fill both of them, my controller receives a string list with 2 items in it. I will add the feature to dynamically add TemoinsVille later.
In my form, I want to use an auto-complete field for this TemoinVille variable. I use a method called 'AutocompleteTous' that works, I use it somewhere else in the form. I don't know how to write the script so that the autocomplete works for a second TemoinVille input.
My JQuery code is:
var auto5 = $('#AdtFormModel_TemoinsVille').autocomplete({
source: '#Url.Action("AutocompleteTous", "InvForm")',
minLength: 3,
delay: 400
}).data("ui-autocomplete");
auto5._renderItem = function (ul, item) {
return $("<li>")
.attr("ui-autocomplete-item", item)
.append(item.label.split("|")[0])
.appendTo(ul);
};
auto5._renderMenu = function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).addClass("dropdown-menu");
};
In my view, I have t TemoinVille textboxfor inputs:
#Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) #Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { #class = "text-danger" })
#Html.TextBoxFor(x => x.AdtFormModel.TemoinsVille, new { Class = "form-control" }) #Html.ValidationMessageFor(x => x.AdtFormModel.TemoinsVille, null, new { #class = "text-danger" })
the autocomplete works for the first input, but not for the second...
Here is the html code for the two inputs:
<div class="invalidite-section">
<input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
</div>
<div class="invalidite-section">
<input Class="form-control" id="AdtFormModel_TemoinsVille" name="AdtFormModel.TemoinsVille" type="text" value="" /> <span class="field-validation-valid text-danger" data-valmsg-for="AdtFormModel.TemoinsVille" data-valmsg-replace="true"></span>
</div>
Any suggestions?
You are targeting an id #AdtFormModel_TemoinsVille, that's the input right?
The ID must be unique on page. So it will work only on first input it finds.
You need to target the elements by class, then the autocomplete should work in all inputs.
try something like this:
var auto5 = $('.form-control input').autocomplete({ // I suppose .form-control is a div that contains the input

Categories

Resources