I have a dropdown meny in a shared layout that have one option that is called "mail me".
Once the "mail me" is pressed, a pop-up modal comes up which can be filled with mail, number and message.
PROBLEM/CHALLENGE: Nothing (viewModel) seems to get passed from my the javascript on the shared layout .cshtml to the back-end. I would like to first of have my values passed to the controller correctly so I can write the info to a file which I then can review and contact whoever filled in the box.
Modal code `
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Kontakt</h4>
</div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="telefonnummer"><span class="glyphicon glyphicon-earphone"></span> Telefonnummer</label>
<input type="number" class="form-control" id="telefonnummer" placeholder="Ange telefonnummer">
</div>
<div class="form-group">
<label for="email"><span class="glyphicon glyphicon-envelope"></span> Email</label>
<input type="text" class="form-control" id="email" placeholder="Ange email">
</div>
<div class="form-group">
<label for="meddelande"><span class="glyphicon glyphicon-pencil"></span> Meddelande</label>
<input type="text" class="form-control" style="height:50px" id="meddelande" placeholder="Ange meddelande">
</div>
<button type="submit" class="btn btn-block" onclick="SkickaMail()">
Skicka
<span class="glyphicon glyphicon-ok"></span>
</button>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal">
<span class="glyphicon glyphicon-remove"></span> Avbryt
</button>
#*<p>Need help?</p>*#
</div>
</div>
</div>
</div>`
"SkickaMail" is supposed to call the Javascript and send a viewModel.
It's suppose to send the val:s to the controller page PeopleController and the IactionResult Kontakt but nothing gets passed to the controller, the vals are null when I debug in the controller.
Code below
<script>
//DEN HÄR DELEN FUNKAR INTE, VÄRDENA SKICKAS INTE KORREKT TILL CONTROLLERN AV NÅGON ANLEDNING.
function SkickaMail() {
var dataX = {
//.val()metoden nedan är jQuery
"#nameof(MVCrepetition.Models.ViewModels.Mail.TelNummer)": $("##nameof(Model.TelNummer)").val(),
"#nameof(MVCrepetition.Models.ViewModels.Mail.EMail)": $("##nameof(Model.EMail)").val(),
"#nameof(MVCrepetition.Models.ViewModels.Mail.Meddelande)": $("##nameof(Model.Meddelande)").val()
}
$.post("/Kontakt", dataX, function (json) {
})
}
</script>
Controller code:
[HttpPost]
public IActionResult Kontakt(Mail viewModel)
{
Mail mail = new Mail();
mail.TelNummer = viewModel.TelNummer;
mail.EMail = viewModel.EMail;
mail.Meddelande = viewModel.Meddelande;
System.IO.File.WriteAllText(#"c:\Users\Administrator\Desktop\LiveTradingProject\mailfromcontact.json", JsonConvert.SerializeObject(mail));
//using (StreamWriter file = File.CreateText(#"c:\movie.json"))
// {
// JsonSerializer serializer = new JsonSerializer();
// serializer.Serialize(file, movie);
// }
return null;
}
I hit the breakpoint on server side but the viewModels values are all null
enter image description here
I hadn't used ID properly in my Modal, that was the issue. The Id's now match the val:s and it works.
Related
I`m quite new with jQuery and looking for advise. How to get data, from jQuery modal (login/password) box to controllers method, and compare with the data in the database and return a response?
There is my login model.
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
Controller methods, where I probably have to get data from modal jQuery.
[HttpGet]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Here is the modal window:
<button type="button" class="btn btn-default btn-lg" id="myBtn">Login</button>
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Login</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form">
<div class="form-group">
<label for="usrname"><span class="glyphicon glyphicon-user"></span> Username</label>
<input type="text" class="form-control" id="usrname" placeholder="Enter email">
</div>
<div class="form-group">
<label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Password</label>
<input type="text" class="form-control" id="psw" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" checked>Remember me</label>
</div>
<button type="submit" class="btn btn-success btn-block" id="confirmPassword"><span class="glyphicon glyphicon-off"></span> Login</button>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
<p>Not a member? Sign Up</p>
<p>Forgot Password?</p>
</div>
</div>
</div>
And jQuery code, where it have to get data from modal box, but it does not work:
$(document).ready(function(){
$("#myBtn").click(function () {
$("#myModal").modal();
});
});
$('#confirmPassword').on('click',
function (e) {
var password = $('.confirmPassword').val();
$.ajax({
url: 'Account/Login',
type: 'GET',
data: { "password": password },
contentType: 'application/json',
dataType: "json",
});
}
Thank you for any advise.
Try this for the HTML and see if it works... Here are the things that I did to attempt to make it work.
Added names on inputs (Name, Email, RememberMe) to match the ViewModel
Added action (~/Account/Login) and method (post) on form tag
Changed button type to submit
Hopefully this will help pass the model to the MVC controller. Set a breakpoint in the first line of the controller Post login method and see if it hits it with Model filled out.
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Login</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form" action="~/Account/Login" method="post">
<div class="form-group">
<label for="usrname"><span class="glyphicon glyphicon-user"></span> Username</label>
<input name="Email" type="text" class="form-control" id="usrname" placeholder="Enter email" >
</div>
<div class="form-group">
<label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Password</label>
<input name="Password" type="text" class="form-control" id="psw" placeholder="Enter password" >
</div>
<div class="checkbox">
<label><input name="RememberMe" type="checkbox" value="" checked>Remember me</label>
</div>
<button type="submit" class="btn btn-success btn-block"><span class="glyphicon glyphicon-off"></span> Login</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
<p>Not a member? Sign Up</p>
<p>Forgot Password?</p>
</div>
</div>
</div>
I am using Codeigniter Framework and now, i have a modal with a form inside of it. Now in my modal footer, i put the submit form for it. It is already outside of the modal. Now why is it doesn't submit in my controller?. I put a var_dump in my controller for it to echo when it was submitted, I am sending it thru without javascript.
Here is my modal with form:
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Category</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<form id="frm_category" class="form-horizontal" method="POST" action="Admin_controls/insertCategory">
<div class="form-group">
<label for="cat_name">Category: </label>
<input type="text" class="form-control" name="cat_name">
</div>
<div class="form-group">
<label for="cat_desc">Description: </label>
<input type="text" class="form-control" name="cat_desc">
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" value="submit" form="frm_category">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
Here is my controller:
public function insertCategory() {
$data = array (
'Category_name' => $this->input->post('cat_name'),
'Category_desc' => $this->input->post('cat_desc')
);
var_dump($data);
}
You should place your submit button before </form>. other wise you need javascript to submit your form
you can use the following code
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Category</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<form id="frm_category" class="form-horizontal" method="POST" action="Admin_controls/insertCategory">
<div class="form-group">
<label for="cat_name">Category: </label>
<input type="text" class="form-control" name="cat_name">
</div>
<div class="form-group">
<label for="cat_desc">Description: </label>
<input type="text" class="form-control" name="cat_desc">
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" value="submit" onclick="myFunction()">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
<script>
function myFunction() {
document.getElementById("frm_category").submit();
}
</script>
You should change the button type to submit. So it can submit the form.
Submit button should be inside of form tag
I have modified your modal code. And I hope it will work
×
Add Category
Category:
Description:
Add
Close
If you want to insert a data then you should follow this step:
To POST or GET you should have add that action attribute in side the <form> tag.
Now For post you need to give address of your controller into the <form action = "<?= base_url('your_controller/your_function') ?>" method="post">.
Now at the controller side:
public function your_function(){
// By using this you can get all posted data at once
$your_post_data = $this->input->post();
// By using this you get the post data seperatedly
$your_post_data = $this->input->post('user_name'); // your form input name
//Now for sending data to the model for database querys
$this->load->model ('your_model');
$data = $this->your_model->your_model_function($your_post_data);
}
if you don't want to load model every time then you can add the model in to __construct
public function __construct() {
parent::__construct ();
$this->load->model ('your_model');
// So now on you just need to call the model name in your function.
}
public function your_function(){
// By using this you can get all posted data at once
$your_post_data = $this->input->post();
// By using this you get the post data seperatedly
$your_post_data = $this->input->post('user_name'); // your form input name
$data = $this->your_model->your_model_function($your_post_data);
}
Now Inside the model:( i am giving example for insert)
public function your_model_function($your_post_data ){
$this->db->insert_batch('your_table_name', $your_post_data );
//If you want to understing of query execuation
// for thie you need to enable the log from config.php form config folde.
//Remove comment from log_message after emeble the log message
//log_message('debug', 'Last Insert query: ' . print_r($this->db->last_query(), TRUE).' Inserted Data: '.print_r($your_post_data, TRUE));
if($this->db->affected_rows() > 0){
return TRUE;
} else {
return FALSE;
}
}
For Mode detail regarding querys please visit this CI documentation
Your Code should be:
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Category</h4>
</div>
<form id="frm_category" class="form-horizontal" method="POST" action="<?= base_utl('Admin_controls/insertCategory') ?>">
<div class="modal-body">
<div class="container-fluid">
<div class="form-group">
<label for="cat_name">Category: </label>
<input type="text" class="form-control" name="cat_name">
</div>
<div class="form-group">
<label for="cat_desc">Description: </label>
<input type="text" class="form-control" name="cat_desc">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" value="submit" form="frm_category">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
Your controller should be:
public function insertCategory() {
// You should have to validate befor insert
$this->load->model ('your_model');
$your_post_data = $this->input->post();
$insert_status = $this->your_model->your_model_function($your_post_data);
if($insert_status == TRUE){
//return to your view or load the view
$this->load->view ('your_view_directory');
} else {
// Send Error Message
}
For Validation Visit this CI documentation
I have a modal that allows users to 'refuel' by filling out a form where they can input the amount of fuel to add, however the maximum fuel amount is 180 litres, so if the existing fuel is 170 litres (the existing fuel value will be retrieved from a database), and the user tries to add 20 litres, it should produce an error. I've got some code already, but it's not producing the error. If anyone could point out the issue it would be greatly appreciated.
$(document).ready(function() {
$('#fuel').blur(function() {
if (!ValidateFuel()) {
e.preventDefault();
}
});
$('#auth_form8').on('submit', function(e) {
if (!ValidateFuel()) {
e.preventDefault();
}
});
});
function ValidateFuel() {
var IsValid = false;
var fuel_to_add = $('#fuel').val();
var current_fuel = '100'; // this value will be retrieved from database
var fuel_once_added = Number(current_fuel) + Number(fuel_to_add);
if (fuel_once_added > 180) {
$('#alertInvalidFuel').show();
IsValid = false;
} else {
$('#alertInvalidFuel').hide();
IsValid = true;
}
return IsValid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-success" role="button" data-target="#confirm-refuelG-EEGU" data-toggle="modal"><em class='fa fa-plus'></em></a>
<div id="confirm-refuelG-EEGU" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Fuel G-EEGU</h4>
</div>
<div class="modal-body">
<form name="auth_form8" id="auth_form8" method="post" action="action_refuel.php">
<p>This action cannot be undone.</p>
<hr>
<input class="form-control" id="aircraft_id" name="aircraft_id" value='1' type="hidden">
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">
Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
<div style="display:none;" class="alert alert-danger" id="alertInvalidFuel">
<p>Fuel will exceed 180 litres.</p>
</div>
<hr>
<div class="form-group has-feedback" name="auth_code8" id="auth_code8">
<label for="auth_code8" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input8" autocomplete="new-password" name="refuel_auth_code" type="password" required>
<span class="form-control-feedback glyphicon" id="iconBad8"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-success">Add Fuel</button>
</div>
</form>
</div>
</div>
</div>
JSFiddle Demo
The problem is here:
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
Your div has id="fuel" and so does the input. Remove the id from the div or make it unique. Also, there is no name attribute for div elements, you should remove that as well.
I'm making a login system using modal dialog from bootstrap 3 and im adding a function to keep the user logged in if they check the checkbox in the modal dialog.
I want to keep a user logged in, even he/she refreshes or closes the browser.
index.php
<div class="container" id="myLogin">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title">PLEASE ENTER YOUR EMAIL ADDRESS AND PASSWORD TO LOG IN.</h5>
</div>
<div class="modal-body">
<div id="show" class="lalert lalert-warning"></div>
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input type="text" name="lemail" id="lemail" value="<?php echo $unm ?>" class="form-control" placeholder="Enter Email Address..." />
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input type="password" name="lpassword" id="lpassword" value="<?php echo $pwd ?>" class="form-control" placeholder="Enter Password..." />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="checkbox" name="chkbox" value="staylogged" class="checkbox-inline" />
<label> Keep me logged in</label> <b>|</b>
Forgot your password?
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="login" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-user"></span> Login</button>
<button type="button" class="btn btn-info show-page modal-btn" data-page="Signup" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-list-alt"></span> Register</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
script:
jQuery(function () {
$("#lemail").val($.cookie("unm"));
$("#lpassword").val($.cookie("pwd"));
});
$("#email").val($.cookie("unm") || "");
$("#lpassword").val($.cookie("pwd") || "");
php:
<?php
session_start();
$unm = $_POST['lemail'];
$pwd = $_POST['lpassword'];
?>
In order to get session_start(); to work,
you need to add variables to the $_SESSION array. Change you PHP code to this:
<?php
//Start the session
session_start();
//ALWAYS check if a $_POST variable is set before using it.
if(isset($_POST['lemail'])){
$unm = $_POST['lemail'];
} else {
//Error Code Goes Here
}
if(isset($_POST['lpassword'])){
$pwd = $_POST['lpassword'];
} else {
//Error Code Goes Here
}
//Set SESSION vars
$_SESSION["unm"] = $unm;
$_SESSION["pwd"] = $pwd;
When you want to check if they are logged in, use this code
session_start();
if(isset($_SESSION["unm"]) && isset($_SESSION["pwd"])){
$loggedIn = true;
//At this point you can also check your database if they are actually a user for extra security
} else {
$loggedIn = false;
}
Please, make sure your cookies is going save or not.
And another thing is make sure of expire time.
set coockies in PHP, like :
setcookie(
'pageVisits', // Name of the cookie, required
$visited, // The value of the cookie
time()+7*24*60*60, // Expiration time, set for a week in the future
'/', // Folder path the cookie will be available for
'demo.tutorialzine.com' // Domain to which the cookie will be bound
);
And Read coockies in JS:
$(document).ready(function(){
// Getting the kittens cookie:
var str = $.cookie('pageVisits');
// str now contains the value of $visited
});
i am using modal in angular but when modal open so here values are not binding with model i don't know why this happening must be appreciates if some corrected if there is any mistake thanx.
modal.html
<script type="text/ng-template" id="categoryModal.html">
<form class="form-horizontal" name="category_form" novalidate>
<div class="modal-header">
<a class="close" ng-click='cancel()'><i class="icon-remove-circle icon-bold"></i> </a>
<h3>Category</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="category_Name" class="col-lg-3 form-label">Category Name:</label>
<div class="col-lg-8">
<input class="form-control" id="category_Name" ng-model="category.name" name="category_Name" placeholder="Category Name" required/>
<div class="error" ng-show="category_form.category_Name.$dirty && category_form.category_Name.$invalid">
<small class="error errorFields" ng-show="category_form.category_Name.$error.required">
Category Name is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button ng-click='saveCategory()' class="btn btn-primary" ng-disabled="category_form.$invalid">
<i class="icon-ok-sign icon-white"></i> Add
</button>
<button ng-click='cancel()' class="btn btn-warning">
<i class="icon-remove-circle icon-white"></i> Cancel
</button>
</div>
</form>
</script>
modalController.js
app.controller('brandModalCtrl', function ($rootScope, $scope, $modalInstance) {
// Save Brand
$scope.saveCategory = function () {
console.log($scope.category) // undefined
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
I would try adding the same $scope to modalOptions and letting the modal share the controller's $scope variables. Putting both onto $rootScope is too drastic. Ideally, your modal should have an isolate scope, but it sounds like you need some overlap.