I am making an MVC 5 web application and I am looking to pass a value from my ViewModel to a function in my JavaScript
The aim is hide a Label/Div when the user selects the option "No" and make it reappear when the user changes the option back to "Yes"
Here is what I have so far:
ViewModel:
public enum BasicAnswer
{
[Display(Name= "Yes")]
Yes,
[Display(Name= "No")]
No
}
public BasicAnswer userDiscomfortResponse { get; set; }
View:
<div id="UserDiscomfortAnswerLabel">
<label id="somelabel">Did you have any discomfort with an exercise?</label>
<div class="Answer1" onclick=feedback data-id='#Model.userDiscomfortResponse'>
#Html.EnumDropDownListFor(m => m.userDiscomfortResponse, new { #class = "form-control" })
</div>
</div>
<div class="Question2">
<label id="UserDiscomfortExerciseLabel">What exercise was the issue?</label>
<div class="Answer2">
#Html.DropDownListFor(m => m.discomfortExercise, Model.UsersSelectedExcerises, new { #class = "form-control" })
</div>
</div>
JavaScript:
function feedback() {
var feedback = $(this).attr('data-id');
if (feedback == "Yes") {
document.getElementById("UserDiscomfortExerciseLabel").style.display = "block"
}
else {
document.getElementById("UserDiscomfortExerciseLabel").style.display = "none"
}
}
The issue I am having is var feedback = $(this).attr('data-id') results as undefined and so the label hides on click but never shows again.
Is there something I've missed?
Thank you in advance.
Ok, try removing the onclick on the div and add:
$(document).ready(function()
{
function feedback() {
var feedback = $('#userDiscomfortResponse').val()
if (feedback == "Yes") {
document.getElementById("UserDiscomfortExerciseLabel").style.display = "block"
}
else {
document.getElementById("UserDiscomfortExerciseLabel").style.display = "none"
}
}
$("#userDiscomfortResponse").change(feedback);
feedback();
}
Related
I have a Remarks div
If user choose option of Other then user need to fill box for reasons.
This is inside webpage(.cshtml)
#model MNepalWeb.Models.CustomerSRInfo
#{
List<SelectListItem> Remarks = new List<SelectListItem>();
Remarks.Add(new SelectListItem { Text = "Your name does not match", Value = "Your name does not match" });
Remarks.Add(new SelectListItem { Text = "Your date of birth does not match", Value = "Your date of birth does not match" });
Remarks.Add(new SelectListItem { Text = "Others", Value = "Others" });
}
//For remarks
<div class="form-group">
<label class="control-label col-md-2">Reject Remarks <b style="color:red;">*</b></label>
<div class="col-md-5">
#Html.DropDownListFor(model => model.Remarks, new SelectList(Remarks, "Value", "Text"), new { #class = "form-control", #style = "width: 100%;", #id = "txtRemarks" })
<br />
<textarea name="OthersRemarks" id="txtOthersRemarks" placeholder="Please Insert Remarks to Reject, maxlength- 200" maxlength="200" rows="4" cols="50" style=" display:none; min-height:50px;min-width:200px;max-height:100px;max-width:422px;" class="form-control" #*oninput="checkValidation()"*#></textarea>
<b style="color:red">*</b><b> Note Please fill out remarks before rejecting </b>
<br />
</div>
</div>
</div>
JS for changing value
if ($.trim($('#RejectRemarks select').val()) == "" || $.trim($('#RejectRemarks select').val()) == "Others") {
var TextBoxRemarks = $("#txtOthersRemarks").val();
if ($.trim($('#RejectRemarks select').val()) == "Others" && TextBoxRemarks.trim() == "") {
document.getElementById("txtOthersRemarks").setCustomValidity("Other Reject Remarks is required");
$('#txtOthersRemarks select').focus();
return;
}
else if ($.trim($('#RejectRemarks select').val()) == "Others" && TextBoxRemarks.trim() != "") {
var txtRemarks = document.getElementById("txtRemarks");
//txtRemarks.value = $("#txtOthersRemarks").val();
txtRemarks.val = TextBoxRemarks;
//txtRemarks.value = TextBoxRemarks;
document.getElementById("txtOthersRemarks").setCustomValidity("");
return;
}
else {
document.getElementById("txtRemarks").setCustomValidity("Reject Remarks is required");
$('#RejectRemarks select').focus();
return;
}
}
else {
document.getElementById("txtRemarks").setCustomValidity("");
}
But when i implement this js it only changes values to checkbox and not send empty value to controller.
public ActionResult BankLinkVerify(UserInfo model, string btnApprove, string Remarks)
I'm trying to find where it goes wrong but could not analysis this. I need whatever user types in text box as remarks value.( default it goes other but when i do that js dropdown value goes null to controller).
Thank You!
Regarding your case, you can access the current value through the Request or FormCollection. You can read your OthersRemarks textarea value from the current Request using Request.Form:
In your Controller method:
string Remarks= Request.Form["OthersRemarks"].ToString()
I found another solution too..
FormCollection can also be used in controller
public ActionResult BankLinkApprove(UserInfo model, string btnApprove, FormCollection collection, string Remarks){
if (Remarks.Equals("Others")){
userInfo.Remarks = collection["OthersRemarks"].ToString();
}
else{
userInfo.Remarks = info.Remarks;
}
}
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);
});
If I create two radio buttons for example:
#Html.RadioButtonFor(model => model.IsFemale, "false") Male
#Html.RadioButtonFor(model => model.IsFemale, "true") Female
How can I show one div when true is pressed, hide it and show another one if false is pressed?
I created pretty simple web site to test this:
#model WebApplication1.Models.Testi
<div>
#Html.RadioButtonFor(model => model.isTest, "false", new { id = "male" })
#Html.RadioButtonFor(model => model.isTest, "true", new { id = "female" })
if (Model.isTest)
{
<div>
Testdiv
</div>
}
</div>
Simple model:
public class Testi
{
public bool isTest { get; set; }
}
You need to use JavaScript. Add an onclick event to the two radio buttons and call a JavaScript function passing the value of the radio button:
#Html.RadioButtonFor(model => model.IsFemale, "false", new { onclick = "showNote(this.value);" }) Male
#Html.RadioButtonFor(model => model.IsFemale, "true", new { onclick = "showNote(this.value);" }) Female
Then add those two divs that you want to show/hide:
<div id="male">Notes for men</div>
<div id="female">Notes for women</div>
And finally add the JavaScript function that will do the job:
<script>
function showNote(isFemale) {
var male = document.getElementById("male");
var female = document.getElementById("female");
if (isFemale == "true") {
female.style.display = "block";
male.style.display = "none";
} else {
male.style.display = "block";
female.style.display = "none";
}
}
</script>
I have this view:
<div class="editor-field">Best</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Best, new List<SelectListItem>
{
new SelectListItem { Value = "Best3", Text = "Best 3"},
new SelectListItem { Value = "Best5", Text = "Best 5"},
new SelectListItem { Value = "Best10", Text = "Best 10"},
new SelectListItem { Value = "XBest", Text = "X Best"}
},
new { #class = "myselect" })
#Html.ValidationMessageFor(model => model.Best)
</div>
<div class="editor-label">X</div>
<div class="editor-field">
#Html.EditorFor(model => model.X)
#Html.ValidationMessageFor(model => model.X)
</div>
And I have this jquery:
$('#Best').on('change', function () {
if ($(this).val() != "XBest") {
$('#X').hide(); //invisible
$('#X').attr('disabled', 'disabled'); // disable
} else {
$('#X').show(); //visible
$('#X').removeAttr('disabled'); // enable
}
});
And it works, but when i go to this view the EditorFor X is always visible, only changes when i start clicking on the values of the dropdownlist. My question is how can it stays hidden when accessing to the view and only shows on click.
You need to execute the change() event immediately after binding the event like following.
$('#Best').on('change', function () {
if ($(this).val() != "XBest") {
$('#X').hide(); //invisible
$('#X').attr('disabled', 'disabled'); // disable
} else {
$('#X').show(); //visible
$('#X').removeAttr('disabled'); // enable
}
}).change(); // auto execute
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'>▼</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