I'm trying to create a customer survey form and I used a bootstrap wizard to navigate through the questions.
So here in the first section, there is a dropdown list for users to select the language.
When the user selects a language I wrote a javascript to get the selected value and pass to the controller and assign it to the session.
So in the next section, I want to show the questions by the selected value which is now stored at the session.
Don't know the method I tried to create this is right or wrong but I realize that it's only read the session data on load.
So is there any way to do this change with the selected value from the first dropdown?
This is the first step
<form action="" id="wizard">
<!-- SECTION 1 -->
<h4></h4>
<section>
<h3>Please select the Language</h3>
<div class="form-row center">
<div class="form-holder center "> #Html.DropDownListFor(model => model.Language, new SelectList(new[] { "English", "සිංහල", "தமிழ்" }),"Please Select the Language", new { #class = "form-control js-dropdown",Id ="DropLanguage" }) </div>
</div>
</section>
This is the script that collects the selected value and passes to the controller to set it to the session
< 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
$.post("/MainDetails/SetSession", {
myVariable: myVar
});
});
}); <
/script>
This is the controller that set the value of the session.
[HttpPost]
public ActionResult SetSession(string myVariable) {
// Set to Session here.
Session["SelectedLanguage"] = null;
if (myVariable == "English") {
Session["SelectedLanguage"] = "Secondary";
} else if (myVariable == "සිංහල") {
Session["SelectedLanguage"] = "Primary";
} else if (myVariable == "தமிழ்") {
Session["SelectedLanguage"] = "Third";
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
So in the next section I tried this,
#if (#Session["SelectedLanguage"].ToString() == "Primary")
{
<h3>Customer Details</h3>
}
else if (#Session["SelectedLanguage"].ToString() == "Secondary")
{
<h3>Customer Details - Language 2</h3>
}
But this if not triggered . it's only triggered with the form load.
Related
I am working on an asp.net MVC core web application, and i added a captcha as follow:-
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<span class="msg-error error"></span>
<div id="recaptcha" class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="#ViewData["ReCaptchaKey"]"></div>
</div>
</div>
also i added the following javascript validation to force a required on the captcha:-
$('#getmyestimate').click(function () {
var $captcha = $('#recaptcha'),
response = grecaptcha.getResponse();
if (response.length === 0) {
$('.msg-error').text("reCAPTCHA is mandatory");
if (!$captcha.hasClass("error")) {
$captcha.addClass("error");
}
} else {
$('.msg-error').text('');
$captcha.removeClass("error");
alert('reCAPTCHA marked');
}
})
as follow:-
but what i am trying to do , is that once the user select the captcha to remove the validation error (if any),, so can anyone advice how i can do so?
You can hide inside your callback recaptchaCallback function that you have already added in data-callback attribute in the g-recaptcha class.
var recaptchaCallback = function() {
$('#recaptcha').removeClass("error");
... //Any other code in the callback
}
Hi i want to do update operation for show and hide div in mvc5 . I will explain my issue with example.
This is my view. In this view i have one field called VisitType. If i clcik the Visit Type as DirectVisit the StartTime and EndTime field will be show(visible) othesewise it will be hide mode.
My Model (Visistors View Mode)
public bool VisitType { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
My View
<div class="col-sm-4" id="VisitType">
<div class="form-group">
<span style="color: #f00">*</span>
#Html.Label("Visit Type", new { #class = "control-label" })
<label>
#Html.RadioButtonFor(model => model.VisitType, "true", new { id = "" }) Telephone
</label>
<label>
#Html.RadioButtonFor(model => model.VisitType, "false", new { id = "" }) Direct Visit
</label>
</div>
</div>
<div id="StartTime">
<div class="col-sm-3">
<div class="foem-group">
#Html.Label("Start Time", new { #class = "control-label" })
#Html.TextBoxFor(model => model.StartTime, new { #class = "form-control ", type = "text" })
#Html.ValidationMessageFor(model => model.StartTime)
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.Label("End Time", new { #class = "control-label" })
#Html.TextBoxFor(model => model.EndTime, new { #class = "form-control ", type = "text" })
#Html.ValidationMessageFor(model => model.EndTime)
</div>
</div>
</div>
My Jquery code
$(document).ready(function () {
$('#StartTime').hide();
$('#VisitType input[type="radio"]').change(function () {
if ($(this).val() === 'false') {
$('#StartTime').show();
}
else {
$('#StartTime').hide();
}
});
});
Now what i want is if i put one entry in my application by selecting the VisitType as Direct Visit and enter StartTime and EndTime ans Saved it. Now i want to change the VisitType as Telephone. So i click the Edit button and once it open the view it have to pass the value to Visit type radio button and also Start Time and end time time also need to be visible with values.
I passed the value to radio buttons in edit mode. But i donno hoe to visible the StartTime and EndTime in edit mode. I donno the exact j-query code. This is the issue. Please any one help me to resolve this issue.
The Code which i tried
Contrroller Code
public ActionResult Edit(Guid ?id)
{
WafeERP_NEWEntities db = new WafeERP_NEWEntities();
VisitorsViewModel objvisitorsviewmodel = new VisitorsViewModel();
View_VisitorsForm objviewvisitorsForm = db.View_VisitorsForm.Find(id);
if (objviewvisitorsForm.VisitType== true)
{
objvisitorsviewmodel.VisitType= true;
}
else
{
objvisitorsviewmodel.VisitType= false;
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "DisplayName", objviewvisitorsForm.EmployeeID);
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "DisplayName", objviewvisitorsForm.CustomerID);
objvisitorsviewmodel.VisitingID = objviewvisitorsForm.VisitingID;
objvisitorsviewmodel.Date = objviewvisitorsForm.VisitingDate;
objvisitorsviewmodel.VisitType= objvisitorsviewmodel.VisitType;
return View(objvisitorsviewmodel);
}
This code pass fetch the value from db and pass it to radio button correctly but now i want to show the starttime and endtime field with values once the view got open by clicking edit button. I tried my level best to explain the issue please any one help me to resolve this issue.
Advance thanks..
You should start by first wrapping the elements in a <div> so that you can show and hide them all rather than having to select all the associated labels, textboxes and validation message placeholders
<div id="date-controls">
#Html.LabelFor(m => m.StartTime)
#Html.TextBoxFor(m => m.STartTime)
....
</div>
and use css to initially hide them
#date-controls {
display:none;
}
then to display them initially if the value of VisitType is true, add the following script
var isVisit = '#Model.ContactMethod';
var dateControls = $('#date-controls');
if (isVisit == 'True') {
dateControls.show();
}
and also modify the script handling the radio buttons to
$('#VisitType input[type="radio"]').change(function () {
var selected = $('#VisitType input[type="radio"]:checked').val();
if (selected == 'true') {
dateControls.show();
} else {
dateControls.hide();
}
});
Side note: Your VisitType property should not be a bool. A bool should only be used for a property to which the answer can only be Yes or No, and the answer to What is the method of contacting us is not Yes or No, its by Telephone, or by Attending a meeting etc. By using a bool it also means that you have no flexibility to add other types in the future (your client might want to offer home visits to incapacitated people, or the option of video conferencing). Instead your property should be a collection or an enum.
Having an issue, I have a partialview named Manage, I load the partial in:
Controller AdminPanel, View AdminProfile like so:
<div id="tab-2" class="tab-pane">
#{Html.RenderPartial("~/Views/Account/Manage.cshtml");
}
</div>
When I click on save changes I get redirected to /Account/Manage, it should be /AdminPanel/AdminProfile?
Not sure if controller is returning the correct redirect or information for the json if I try to use a ajax script:
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
public ActionResult Manage(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("AdminProfile", "AdminPanel");
//ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("AdminProfile", "AdminPanel", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("AdminProfile", "AdminPanel", new { Message = ManageMessageId.ChangePasswordSuccess });
}
catch (Exception)
{
ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
}
}
}
// If we got this far, something failed, redisplay form
//return PartialView("Manage", model);
return Json(new { redirectTo = Url.Action("AdminProfile", "AdminPanel") });
}
This is the partial page that is loaded:
#model LocalPasswordModel
#{
ViewBag.Title = "Change Password";
}
<section class="hgroup">
<div class="panel-body">
<h1>#ViewBag.Title</h1>
<ul class="breadcrumb pull-right top-right">
<li>You're logged in as <strong>#User.Identity.Name</strong></li>
</ul>
<ul class="message-success">#ViewBag.StatusMessage</ul>
#using (Html.BeginForm("Manage", "Account", Form.Post, new { #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label class="col-sm-2 control-label">Old Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.OldPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.NewPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-2">
<input type="submit" class="btn btn-primary" value="Change password" />
</div>
</div>
}
</div>
</section>
The script below is placed in the _LayoutPage however as mentioned in the comments it is not doing anything.
<script type="text/javascript">
$.ajax({
type: "POST",
url: '#Url.Action("Manage", "Account")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
// The operation was a success on the server as it returned
// a JSON objet with an url property pointing to the location
// you would like to redirect to => now use the window.location.href
// property to redirect the client to this location
window.location.href = result.redirectTo;
} else {
// The server returned a partial view => let's refresh
// the corresponding section of our DOM with it
$(".tab-2").html(result);
}
},
error: function () {
}
});
</script>
All I am trying to do is stop the redirect after I submit, I have opened this to a bounty. It would be nice if you could also include how I could recieve the status messages back aswell after a user hits submit.
For instance user hits save changes > saves to the server > messages are then sent back to the partial page (all without redirecting)
Firstly, you need to decorate your POST action result as a post.
[HttpPost]
public ActionResult Manage(LocalPasswordModel model){
Secondly, you can get rid of the javascript altogether by
testing the validity of the form submit result within your controller
and this will manage whether the user is redirected or not.
[HttpPost]
public ActionResult Manage(LocalPasswordModel model){
if(condition to redirect){
return RedirectToAction("AdminProfile", "AdminPanel");
}
return View(model);
}
Lastly, I cannot see where you've actually put you jquery.
It needs to be put at the end of your form page, in your script section.
You mention it's in your layout page?
I think this link may also help, jQuery.post(), also event.preventDefault() is also useful to prevent form submission client side.
To control specifically where you want to redirect to, add redirects at every place there is a result, example: please note I am only returning to the adminprofile as this is what the op wants
if (changePasswordSucceeded)
{
return RedirectToAction("AdminProfile", "AdminPanel", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
return RedirectToAction("AdminProfile", "AdminPanel");
}
As a sidenote, you need to think through your program flow to decide how you want to manage invalid attempts, etc.
Is it because when you press save its doing a regular http post to the server to the Account/Manage page so you are being redirected. So your javascript is never actually running?
try using Ajax.BeginForm or changing the save button to use your javascript.
If you are posting your form data using AJAX then simply in the submit function
<form onsubmit="mysubmitfunc(event)" ....>
And in the submit function
function mysubmitfunc(e)
{
e.preventDefault();
/*
YOUR AJAX CODE GOES HERE
*/
return false; //last line in the function
}
Use ajax submit in the right way, how? attach to form submission event, catch submit event, stop the post, post it from javscript, and process the response at success.
Replace your _LayoutPage js with next, make sure you are using ID to identify the form, if not this javascript may affect other forms.
$(function() { //shorthand document.ready function
//recommended to use Id on form identification not class... search on google how to
//attach handler on form submit
$('.form-horizontal').submit(catchSubmit);
//custom handler for form submit
function catchSubmit(event) {
event.preventDefault(); //stop html form post
// ajax post with serialized form
$.post($(this).attr("action"),
$(this).serialize(),
postSuccessHandler
);
}
//redirect decizion
function postSuccessHandler(data) {
if (data.redirectTo) {
window.location.href = data.redirectTo;
} else {
$(".tab-2").html(data);
}
}
});
You can also move the html button to outside of the form.
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() { ...
Problem Statement: I want to change the display name of labels(#Html.LabelFor) in Razor view of MVC based on the display names which i get from db.
I have added the dropdown list of languages in the _Layout.cshtml
<li>#Html.Action("Index", "LanguageDropdown", new { languageid = Request["languageId"] })</li>
I have created one partial view for drop down:
#model ALCMS.Web.Models.Master_or_Configuration.LanguageDropdownModel
<script type="text/javascript">
function GetLanguage() {
var languageId = $('#LanguageId').val();
var Url = "#Url.Content("~/MasterConfigGeneral/GetLanguage")";
$.ajax({
url: Url,
dataType: 'json',
data: { LanguageId: languageId },
success: function (data) {
}
});
}
</script>
<div style="display:inline-block">
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
</div>
Partial View Controller:
public ActionResult Index(string languageId)
{
//return View();
var languages = dbEntity.LookupLanguages;
var model = new LanguageDropdownModel
{
LanguageID = languageId,
Languages = languages.ToList().Select(l => new SelectListItem
{
Value = Convert.ToString(l.LanguageID),
Text = l.Name
})
};
return PartialView(model);
}
In Controller Json Result method:
public JsonResult GetLanguage(int languageID)
{
JsonResult jsResult = new JsonResult();
objdbGlobalTenant.ddlLanguage = (from lsr in dbEntity.LocaleStringResources
where lsr.LanguageID == languageID
select new SelectListItem()
{
Text = lsr.ResourceValue,
Value = lsr.ResourceName
}).Distinct().ToList<SelectListItem>();
//ViewBag.Language = objdbGlobalTenant.ddlLanguage;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
Now everything is working fine.I'm able to get the selected langaugeID in Json Result method in Controller based on the change event of Language dropdown. Based on this Language ID i'm getting display names(ResourceValue) which i need to apply for the particular view.
Problems:
1>After getting the display names from db how to change display names
of particular view when language change event triggers.?? For
ex:Currently i'm seeing the Create.CSHTML. Now if i change the
language dropdown it should trigger Json Event in controller and
after getting values it should apply the values on the view which it
got from db.
Note: Dropdown is in Layout.cshtml(like master in .aspx)
2>Drop-down which i placed in Layout.cshtml is getting refreshed
every time new view is loaded which inherits(layout.cshtml).How to
make the controller to retain it's state during postback??
3>How to get the selected drop-down item from the layout in multiple
Controllers,to change the display name in each view based on the langaugeid
of dropdown in layout
How to do this??If i'm doing wrong suggest me some other ways...
Below are the suggestions :
Issue 1 :
You may keep one attribute in each label which identifies them uniquely.
Your HTML should render like following
<!-- For English -->
<label label-unique-name="Name">Name</label>
<label label-unique-name="Surname">Surname</label>
<!-- For French -->
<label label-unique-name="Name">nom</label>
<label label-unique-name="Surname">nom de famille</label>
<!-- For Spanish -->
<label label-unique-name="Name">nombre</label>
<label label-unique-name="Surname">apellido</label>
Here label-unique-name is your attribute, which will remain fixed for each language. Now when you change the language from dropdown you will bring the values like below.
<!-- For English -->
<label-unique-name:"Name",label-value:"Name">;<label-unique-name:"Surname",label-value:"Surname">
<!-- For French -->
<label-unique-name:"Name",label-value:"nom">;<label-unique-name:"Surname",label-value:"nom de famille">
<!-- For English -->
<label-unique-name:"Name",label-value:"nombre">;<label-unique-name:"Surname",label-value:"apellido">
Please note : this is for understanding only, it's not a JSON.
Now using jQuery go through each label and replace the label's value. Hope it'll help you.
Issue 2 :
You can save the selected language's value in session, and generate your dropdown accordingly.
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), !string.isNullorEmpty(HttpContext.Current.Sessions["Language"]) ? HttpContext.Current.Sessions["Language"] : "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })