I am using the CaptchaMvc.Mvc5 library.
I created a partial view to show the verification code generated by the Captcha, which is activated by #Ajax.ActionLink
When the verification code is wrong, the new code is not generated and generates the following error:
Failed to load resource: the server responded to a status of 500 (Internal Server Error) http: // localhost: 2755 / DefaultCaptcha / Refresh
partial view call
#Ajax.ActionLink("PROCESAR PEDIDO", "ValidarCaptcha", "Principal",
new AjaxOptions {
HttpMethod = "GET",
UpdateTargetId = "ModalCaptcha"
},
new {
#class = "btn btn-flat btn-block",
data_toggle = "modal",
title = "Validar Captcha",
#data_target = "#ModalCaptcha",
#id = "btnprocesarpedido"
})
Partial view
#using CaptchaMvc.HtmlHelpers
<div class="modal-dialog modal-dialog-centered modal-sm" role="document">
<div class="modal-content padding10px">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></button>
<h5 class="modal-title font-bold">Title </h5>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
#using ( Ajax.BeginForm("ValidarCaptcha", "Principal", new AjaxOptions() { UpdateTargetId = "MensajeAlert", HttpMethod = "Post", InsertionMode = InsertionMode.Replace, OnSuccess = "OnAjaxSuccessCaptcha" }) )
{
#Html.Captcha("Refrescar", "Ingrese el texto que ve arriba:", 4, "Campo requerido", false)
<div class="form-horizontal">
<div class="paddingtop15px">
<div id="msjcaptcha"></div>
<input type="submit" value="Enviar" class="btn btn-primary btn-flat" />
</div>
</div>
}
</div>
</div>
</div>
</div>
</div>
Action Controller
[HttpPost]
public ActionResult ValidarCaptcha(string CaptchaInputText)
{
int _result = 0;
string _mensaje = string.Empty;
string _url = string.Empty;
try
{
if ( this.IsCaptchaValid(CaptchaInputText.ToUpper()) )
{
_result = 1;
_url = new UrlHelper(Request.RequestContext).Action("PedidoProcesado", "Principal");
}
else
{
_mensaje = "Captcha inválido";
}
}
catch ( Exception ex )
{
Utility.RegistrarExcepcion("PrincipalController", "HttpPost()-ValidarCaptcha()", ex.ToString(), Request.Browser.Browser.ToString(), Request.Browser.Version.ToString());
}
return Json(new { result = _result, msj = _mensaje, url = _url }, JsonRequestBehavior.AllowGet);
}
enter image description here
Related
I am going to pass external object list with form-data in submitHandler section. When i am passing form object only it is working properly. but i want to add list of object to that ajax post request.
JS
submitHandler: function (e) {
$(".loader-showhide").show();
var contacts = [
{ name: 'test 1', mobile: '11111111' },
{ name: 'test 2', mobile: '22222222' }
];
var dataToPost = JSON.stringify({ contacts: contacts });
var form = $(e);
form.find(":submit").attr("disabled", true);
$.ajax(form.attr("action"),
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: { model: $(form).serialize(), contacts: dataToPost },
cache: false,
success(data) {
$(".loader-showhide").hide();
$("#myModal").modal('hide');
var table = $('#dt_account').DataTable();
table.ajax.reload();
toastr.success('Successfully added.');
$('#submitBtn').prop("disabled", false);
},
error(xhr) {
}
});
}
Controller
[HttpPost]
public ActionResult Create(ActivityViewModel model, List<Contact> contacts)
{
try
{
int result = 0;
return Json(new { StatusCode = result });
}
catch (Exception ex)
{
throw ex;
}
}
Object
public class Contact
{
public string Name { get; set; }
public string Mobile { get; set; }
}
Here is my form, I used jquery datatable and jquery form submit with submit handler.
<form action="#Url.Action("Create", "Activity")" id="account-form" method="POST" novalidate="novalidate" enctype="multipart/form-data">
<div class="form-blocker-wrap">
#Html.HiddenFor(o => o.Id)
<div class="card-block row">
<div class="col-lg-12">
<div class="scroller bottom-box px-3">
<div class="row">
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="Name">Activity Name</label>
#Html.TextBoxFor(o => o.Name, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="StartDateTime">Start Date</label>
#Html.TextBoxFor(o => o.StartDateTime, new { type = "date", maxlength = 100, placeholder = "Start Date", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="EndDateTime">End Date</label>
#Html.TextBoxFor(o => o.EndDateTime, new { type = "date", maxlength = 100, placeholder = "End Date", #class = "form-control", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="ContactType">Select Method</label><br />
#Html.DropDownListFor(o => o.ContactType, (IEnumerable<SelectListItem>)Model.ContactList, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", #onchange = "ChangeMethod(this)", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div disabled class="col-md-6 grl-section">
<div class="col-lg-12 form-group">
#for (int i = 0; i < Model.GRLContactGroupList.Count(); i++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].IsChecked) #(#Model.GRLContactGroupList[i].GroupName + " - " + #Model.GRLContactGroupList[i].ZONE) <br />
#for (int j = 0; j < Model.GRLContactGroupList[i].GRLContactList.Count(); j++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].GRLContactList[j].IsChecked) #Model.GRLContactGroupList[i].GRLContactList[j].Name <br />
}
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer modal-footer py-4">
<div class="row">
<div class="col-lg-6 px-4">
<button id="submitBtn" type="submit" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-default color-theme">Clear</button>
</div>
</div>
</div>
</form>
I'm trying to get the routes working but no matter what I do I always get sent back to the login form.
It does however switch to the profile view. But not to any of the other views.
The Action
[HttpPost]
public ActionResult Authorise(tblUser user)
{
using (TrinityEntities db = new TrinityEntities())
{
var userEmail = db.tblUsers.Where(x => x.Email == user.Email).FirstOrDefault();
var userPassword = db.tblUsers.Where(y => y.Password == user.Password).FirstOrDefault();
//Check if email registered
//if (userEmail == null)
//{
// ViewBag.LoginIncorrect = "E-mail not registered, do you want to register?";
// return View("Index", user);
//}
//check login correct
if (userEmail == null && userPassword == null)
{
ViewBag.LoginIncorrect = "E-mail or Password not correct";
return View("Index", user);
}
//Everything is correct so login
//else if(userEmail.ToString() == user.Email && userPassword.ToString() == user.Password)
//{
// Session["User ID"] = user.Id;
// return RedirectToAction("Index", "Home");
//}
else
{
//Session["UserID"] = user.Id;
////int userID = user.Id;
//if (user.BIO == null )//|| user.Preffered == null || user.Sex == null || user.BIO == null)
//{
// return RedirectToAction("index", "Chat");
//}
//return RedirectToAction("Index", "Home");
return Redirect("/chat");
}
}
}
The login View
#model Trinity.Models.tblUser
#{
ViewBag.Title = "Login";
}
<h2>Login</h2>
#using (Html.BeginForm("Authorise", "Auth", FormMethod.Post))
{
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Login" class="btn btn-default" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<label class="label-warning">#ViewBag.LoginIncorrect</label>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The chat view
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>pChat — Private Chatroom</title>
<link rel="stylesheet" href="#Url.Content("~/Content/app.css")">
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">pChat - #ViewBag.currentUser.name </a>
</div>
<ul class="nav navbar-nav navbar-right">
<li>Log Out</li>
</ul>
</div>
</nav>
<!-- / Navigation Bar -->
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-3">
<aside class="main visible-md visible-lg">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default users__bar">
<div class="panel-heading users__heading">
Contacts (#ViewBag.allUsers.Count)
</div>
<div class="__no__chat__">
<p>Select a contact to chat with</p>
</div>
<div class="panel-body users__body">
<ul id="contacts" class="list-group">
#foreach (var user in #ViewBag.allUsers)
{
<a class="user__item contact-#user.id" href="#" data-contact-id="#user.id" data-contact-name="#user.name">
<li>
<div class="avatar">
<img src="#Url.Content("~/Content/no_avatar.png")">
</div>
<span>#user.name</span>
<div class="status-bar"></div>
</li>
</a>
}
</ul>
</div>
</div>
</div>
</div>
</aside>
</div>
<div class="col-xs-12 col-md-9 chat__body">
<div class="row">
<div class="col-xs-12">
<ul class="list-group chat__main"></ul>
</div>
<div class="chat__type__body">
<div class="chat__type">
<textarea id="msg_box" placeholder="Type your message"></textarea>
<button class="btn btn-primary" id="sendMessage">Send</button>
</div>
</div>
<div class="chat__typing">
<span id="typerDisplay"></span>
</div>
</div>
</div>
</div>
</div>
<script src="#Url.Content("~/Content/app.js")"></script>
</body>
</html>
<script>
etc....
And the route config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Auth", action = "Index", id = UrlParameter.Optional }
);
//routes.MapRoute(
// name: "Default",
// url: "",
// defaults: new { controller = "Auth", action = "Index", id = UrlParameter.Optional }
//);
routes.MapRoute(
name: "Profile",
url: "profile",
defaults: new { controller = "Profile", action = "Index" }
);
routes.MapRoute(
name: "Home",
url: "Home",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "ChatRoom",
url: "chat",
defaults: new { controller = "Chat", action = "index" }
);
routes.MapRoute(
name: "GetContactConversations",
url: "contact/conversations/{contact}",
defaults: new { controller = "Chat", action = "ConversationWithContact", contact = "" }
);
routes.MapRoute(
name: "PusherAuth",
url: "pusher/auth",
defaults: new { controller = "Auth", action = "AuthForChannel" }
);
routes.MapRoute(
name: "SendMessage",
url: "send_message",
defaults: new { controller = "Chat", action = "SendMessage" }
);
routes.MapRoute(
name: "MessageDelivered",
url: "message_delivered/{message_id}",
defaults: new { controller = "Chat", action = "MessageDelivered", message_id = "" }
);
}
}
I just want it to switch to the other views which for some reason I cant get to work.
After verifying users credentials you need to store the cookie :
else
{
//Session["UserID"] = user.Id;
////int userID = user.Id;
//if (user.BIO == null )//|| user.Preffered == null || user.Sex == null || user.BIO == null)
//{
// return RedirectToAction("index", "Chat");
//}
//return RedirectToAction("Index", "Home");
**FormsAuthentication.SetAuthCookie(username, false);**
return Redirect("/chat");
}
Edit: I got how to refresh the page on success, but it just creates 2 calls to my controller method, which is unnecessary and the page doesn't update on 1st call. Can anyone help to update the page on first call?
Now I am new to Ajax calls so, I don't know how to refresh my view Or Webgrid after executing my controller method.
And I am also unable to find whether success method is called or not in Ajax.
And I am facing this in every Ajax call, why View isn't updated when returned by controller method.
What I have done is, there is a DropDownlist,and on selecting a value and submitting displays a webgrid.
Webgrid has checkboxes and on selecting checkboxes and clicking on submit passes some data through AJax to controller method. The Data gets updated in DataBase but it is not reflected in view Until I refresh it.
How to refresh View automatically?
Any help would be appreciated.
I have a View as follows:
$("#save_btn").on("click", function () {
var ischecked = 0;`enter code here`
$('#tblFormentry').find("input:checkbox").each(function () {
if (this.checked) {
var chck = $(this).attr("value");
var hidden = $(this).closest('td').find(':hidden');
villcode = villcode + "," + hidden.val();
singlestring = singlestring + "," + chck;
}
});
if ((singlestring != null && singlestring != "") && (villcode != null && villcode != "")) {
alert(singlestring);
if (confirm("Are you sure?") == true) {
$.ajax({
url: "#Url.Action("getmultipleids", "Admin")",
contentType: "application/json; charset=utf-8",
data: { 'ids': singlestring, 'villcode': villcode },
type: "GET",
cache: false,
success: function (result) {
$("body").html(result);
singlestring = "";
villcode = "";
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
else {
singlestring = "";
}
}
else {
alert("Please select at least 1 Entry!");
}
});
<div class=" col-md-10">
#using (Html.BeginForm("GetGridData", "Admin", FormMethod.Post, new { #id = "verifyentry_form", role = "form" }))
{
#*#Html.ValidationSummary(false, "", new { #class = "text-danger" })*#
if (!string.IsNullOrEmpty(Convert.ToString(TempData["ErrorMessage"])))
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Error! </strong>#TempData["ErrorMessage"].ToString()
<div style="display:none">#TempData.Remove("ErrorMessage")</div>
</div>
}
if (!string.IsNullOrEmpty(Convert.ToString(TempData["Message"])))
{
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong></strong>#TempData["Message"].ToString()
<div style="display:none">
#TempData.Remove("Message")
</div>
</div>
}
<div class="panel-default box box-primary">
<div class="panel-heading">
<h2 class="panel-title">Verify Entry</h2>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.agency_id, new { #class = "control-label" })
#*#Html.DropDownListFor(m => m.DistID, (SelectList)TempData["Districts"], "Select", new { #class = "form-control" })*#
#Html.DropDownListFor(model => model.agency_id, (SelectList)#ViewBag.Agencylist, "Select", new { #class = "form-control", #id = "ddID" })
</div>
</div>
<div class=" row ">
<input type="button" name="submitbtn" value="Submit" class="btn btn-primary" id="databtn" />
</div>
</div>
</div>
}
<div class="box box-primary" id="ajaxdiv">
#if (ViewBag.formentry != null)
{
int PageSizeValue = 1;
//if (!string.IsNullOrEmpty(Convert.ToString(Session["Tbl_TraMstPageSizeValue"])))
//{
// PageSizeValue = Convert.ToInt32(Session["Tbl_TraMstPageSizeValue"]) > 0 ? Convert.ToInt32(Session["Tbl_TraMstPageSizeValue"]) : 1;
//}
WebGrid grid = new WebGrid(ViewBag.formentry, ajaxUpdateContainerId: "ajaxdiv", rowsPerPage: 10, ajaxUpdateCallback: "DetailsUpdate");
#grid.GetHtml(
htmlAttributes: new { id = "tblFormentry" },
tableStyle: " table table-bordered table-hover dataTable", headerStyle: "",
mode: WebGridPagerModes.All,
firstText: "<<",
lastText: ">>",
nextText: ">",
previousText: "<",
columns: new[]{
#*grid.Column(header:"{checkall}",format:#<text>
<input type="checkbox" name="Tbl_TraMstId" value="#item.agency_id" onclick="CheckClick(this)" />
</text>,style:"TableCheckBoxStyle",canSort:false),*#
grid.Column("district_name","District Name",canSort:false),
grid.Column("block_name","Block Name",canSort:false),
grid.Column("village_name","Village Name", canSort:false),
grid.Column("name","Name", canSort:false),
grid.Column("formno","Form No", canSort:false),
grid.Column("agency_name","Agency Name", canSort:false),
//grid.Column("Verify", format: (item) => item.GetSelectLink(item.formno)),
grid.Column("Verify",format:#<text>
<form method="post" action="" id="chckboxform">
<input type="hidden" name="village_code" value="#item.village_code" />
<input type="checkbox" name="formno" value="#item.formno" id="chckbox1" />
</form>
</text>,style:"tablebutton",canSort:false)
})
}
</div>
<input type="button" name="submit" value="Submit" id="save_btn" class="btn btn-primary" />
<input type="button" name="reset" value="Reset" id="reset_btn" class="btn btn-primary" />
Following is the controller method that is being called with the help of jQuery AJax call.
public ActionResult getmultipleids(string ids, string villcode)
{
//need verificatN date, verified, verification user = admin, formno, villagecode
int i;
string[] formno = ids.Split(',');
string[] village_code = villcode.Split(',');
DataTable dt = new System.Data.DataTable("Entries");
DateTime today = DateTime.Today;
DataRow dr;
DataColumn dc;
dt.Columns.AddRange(new DataColumn[5] {
new DataColumn("verification_date", typeof(DateTime)),
new DataColumn("verified", typeof(Char)),
new DataColumn("verification_user", typeof(string)),
new DataColumn("formno", typeof(Int64)),
new DataColumn("village_code", typeof(string))
});
for (i = 1; i < formno.Count(); i++)
{
dr = dt.NewRow();
dr["verification_date"] = today;
dr["verified"] = 'Y';
dr["verification_user"] = "admin";
dr["formno"] = Int64.Parse(formno[i]);
dr["village_code"] = village_code[i];
dt.Rows.Add(dr);
}
try
{
actionResult = objfamilyBAL.Update_Entry(dt);
TempData["Message"] = actionResult.Message;
ViewBag.Agencylist = (SelectList)Session["ddlist"];
if (ShowResultMessage(actionResult, true, false))
{
int op = 1;
int agncyid = (int)Session["agency_id"];
String WorkArea = Session["wrkArea"].ToString();
actionResult = objfamilyBAL.Fetch_verify_griddata(op, agncyid, WorkArea);
if (actionResult.IsResult)
{
List<CommonTableEntity> family_entitylist = (List<CommonTableEntity>)actionResult.ObjResult;
ViewBag.formentry = family_entitylist;
}
}
if (actionResult.IsErrorMessage)
{
TempData["ErrorMessage"] = actionResult.ErrMessage;
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View("VerifyEntry");
}
Sorry for long post.
In my layout page i have used Request.IsAuthenticated method to show login and logout link.Login link poppup modal with the Login form.( modal popup is in partial page).
After successfully logged in logout link will show up. When i hit the logout l it goes to the logoff method and redirect to Index action but it doesn't goes to the view instead it shows same view.
Pleaseadvise me. I have spend lots of hour to fixed this
Layout page
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
#if (Request.IsAuthenticated)
{
<div>
Loggen As: #User.Identity.Name
</div>
<a id="logOut" style="cursor:pointer">
<span class="glyphicon glyphicon-log-out"></span> Logout
</a>
}
else
{
<div>
Loggen As: #User.Identity.Name
</div>
<a style="cursor:pointer" data-toggle="modal" data-target="#loginModal">
<span class="glyphicon glyphicon-log-in"></span> Login
</a><h3>dsdasdasddsad</h3>
}
</li>
</ul>
</div>
</div>
</nav>
<div id="loginModal" class="modal fade" data-backdrop="static" data-keyboard="false" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
#Html.Partial("_LoginModal")
</div>
<div class="modal-footer">
<button id="Login" type="button" class="btn btn-success">Login</button>
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<section id="main">
#RenderBody()
<p>Copyright W3schools 2012. All Rights Reserved.</p>
</section>
<script type="text/javascript">
$('#logOut').click(function () {
$.post("#Url.Action("Logoff", "Home")", function (data) {
});
});
$('#Login').click(function (evt) {
evt.preventDefault();
var _this = $(this);
var _form = _this.closest("form");
var validator = $("form").validate();
var anyError = false;
$('#LoginForm').find("input").each(function () {
if (!validator.element(this)) {
anyError = true;
}
});
if (anyError)
return false;
var form = $('#LoginForm').serialize();
$.ajax({
type: "POST",
url: '/Home/Index',
data: form,
dataType: "json",
success: function (response) {
if (response.isRedirect && response.isUser) {
// alert('1');
window.location.href = response.redirectUrl;
}
else if (response.isRedirect && response.isAdmin) {
// alert('2');
window.location.href = response.redirectUrl;
}
else if (!response.isRedirect) {
$('#LoginForm').find("#message").text(response.errorMessage);
}
},
error: function (response) {
alert("Some error");
}
});
});
</script>
partial page: which is inside shared folder
#model WebApplication6.ViewModel.LoginViewModal
#using WebApplication6.ViewModel
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #id = "LoginForm", #class = "form-horizontal" }))
{
#Html.ValidationSummary(true, "Login failed. Check Login details")
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-sm-3 control-label" })
<div class="col-sm-9">
#Html.TextBoxFor(x => x.UserName, new { #class = "form-control", #placeholder = "Enter UserName" })
#Html.ValidationMessageFor(x => x.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-sm-3 control-label" })
<div class="col-sm-9">
#Html.PasswordFor(x => x.Password, new { #class = "form-control", #placeholder = "Enter UserName" })
#Html.ValidationMessageFor(x => x.Password)
</div>
</div>
<div class="form-group">
#Html.Label("User Type", new { #class = "col-sm-3 control-label" })
<div class="col-sm-3">
#Html.DropDownList("userType",
new SelectList(Enum.GetValues(typeof(UserType))), new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div id="message" style="color:#ff0000; font-weight:bold;" class="col-sm-offset-3 col-sm-12">
</div>
</div>
}
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApplication4.Helper;
using WebApplication6.Models;
using WebApplication6.ViewModel;
namespace WebApplication6.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(LoginViewModal lm)
{
CareManagementEntities db = new CareManagementEntities();
if (ModelState.IsValid)
{
var userActive = db.Usrs.Where(x => x.Usr_Nm == lm.UserName && x.IsActive == true && x.IsDeleted == false).FirstOrDefault();
if (userActive != null)
{
var userss = db.Usrs.Where(x => x.Usr_Nm.ToLower() == lm.UserName.ToLower()).FirstOrDefault();
var validPassword = PasswordHelper.ValidatePassword(lm.Password, userss.Usr_Pwd);
if (validPassword)
{
var users = db.Usrs.Where(x => x.Usr_Nm == lm.UserName).FirstOrDefault();
if (users != null)
{
var userWithRole = db.Usrs.Where(x => x.Usr_Nm == lm.UserName && x.Usr_Role == lm.userType.ToString()).FirstOrDefault();
if (userWithRole != null)
{
if (userWithRole.Usr_Role == "Admin")
{
FormsAuthentication.SetAuthCookie(lm.UserName, false);
return Json(new
{
redirectUrl = "/Admin/Index",
isRedirect = true,
isAdmin = true,
});
}
else if (userWithRole.Usr_Role == "User")
{
return Json(new
{
redirectUrl = "/UserPage/Index",
isRedirect = true,
isUser = true,
});
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
else
{
return Json(new
{
isRedirect = false,
errorMessage = "The user name or password provided is incorrect."
});
}
}
return Json(new
{
isRedirect = false,
errorMessage = "Error happen please reload the page"
});
}
public ActionResult Logoff()
{
FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
FormsAuthentication.RedirectToLoginPage();
return RedirectToAction("Index", "Home");
}
}
}
I making an ajax call and ajax calls stay on the same page. So i replace the ajax call with action link that works for me.
Thank you Stephen Muecke for your quick right answer.
As can be seen in this picture I have a list of missing dates I have not reported a time for, and when I click a date I have missed my 'Rappotera tid' gets filled in with that date.
But what I want to do is I want to remove my 'Datum' have it sole based on the check boxes that are before the date, so at at a later date can report several dates at once.
But I am stuck and I would like to get some help.
This is my view:
<script type="text/javascript" language="javascript">
$(function() {
$(function() {
$('#date').datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd",
firstDay: 1,
onSelect: function(dateText) {
$('#EndDate').datepicker('option', 'minDate', new Date(dateText));
}
});
});
});
function SetDate(dt) {
$('#date').val(dt);
}
var n = #(Model.Projects.Count);;
function AddProject() {
n++;
$.ajax({
type: "GET",
url: "#Url.Action("Project")/" + n,
dataType: "html",
success: function(data) {
$('#projects').append(data);
}
});
}
$(function() {
$('#startTime').change(function() { CalculateTime(); });
$('#endTime').change(function() { CalculateTime(); });
$('#breakTime').change(function() { CalculateTime(); });
CalculateTime();
});
function CalculateTime() {
try {
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var breakTime = $('#breakTime').val();
var startDate = new Date(2000, 1, 1, startTime.substring(0, 2), startTime.substring(3, 5), 0, 0);
var endDate = new Date(2000, 1, 1, endTime.substring(0, 2), endTime.substring(3, 5), 0, 0);
var time = endDate - startDate;
time = time / 1000 / 60 / 60;
time = time - breakTime.substring(0, 2);
time = time - (breakTime.substring(3, 5) / 60);
$('#workedHours').html(time + " timmar");
} catch (err) {
$('#workedHours').html("---");
}
}
</script>
<div class="page-container">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
#if (ViewData["posted"] != null)
{
<div class="alert alert-success">
<strong>Tidsrapporten tillagd.</strong>
</div>
}
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">missad rappoterad tid</span>
</div>
</div>
<form class="form-horizontal">
<div class="portlet-body form">
<div class="form-group">
#foreach (var date in ViewBag.MissingDays)
{
var isoDate = date.ToString("yy-MM-dd");
<div class="col-md-1">
<input type="checkbox" name="Date" value="Date">
#isoDate
</div>
}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#Html.ValidationSummary()
#using (Html.BeginForm("TimeReport", "Reports", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal" }))
{
#Html.Hidden("ReportId", Model.ReportId)
<div class="col-md-6">
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">Rappotera tid</span>
</div>
</div>
<div class="portlet-body form">
<div class="form-group">
<label class="col-md-3 control-label">Datum:</label>
<div class="col-md-5">
#Html.TextBox("date", Model.Date.ToShortDateString(), new {#class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Start tid:</label>
<div class="col-md-5">
#Html.TextBox("startTime", Model.Times.StartTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Slut tid:</label>
<div class="col-md-5">
#Html.TextBox("endTime", Model.Times.EndTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Rast Längd:</label>
<div class="col-md-5">
#Html.TextBox("breakTime", Model.Times.BreakTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Tid jobbad:</label>
<div class="col-md-5">
#Html.TextBox("workedHours", Model.Times.WorkedHours, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div id="projects">
#foreach (var data in Model.Projects)
{
Html.RenderPartial("Project", data, ViewData["vd"] as ViewDataDictionary);
var viewDataDictionary = ViewData["vd"] as ViewDataDictionary;
if (viewDataDictionary != null)
{
viewDataDictionary["id"] = (int)viewDataDictionary["id"] + 1;
}
}
</div>
</div>
<div class="form-actions">
<div class="col-md-offset-4 col-asdfasmd-9">
Lägg till projekt
<button type="submit" class="btn btn-primary">Spara</button>
</div>
</div>
if (Model.ReportId.HasValue)
{
<input type="submit" value="Ta bort" name="delete" />
}
}
</div>
</div>
</div>
</div>
And this is my controller for this view:
public ActionResult TimeReport(FormCollection form, Guid? id)
{
ViewDataDictionary vd = new ViewDataDictionary
{
["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
["id"] = 1,
["showDescription"] = true
};
ViewData["vd"] = vd;
NewTimeReportModel projectData = new NewTimeReportModel();
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
LoadDefaultSettings(projectData);
ViewData.Model = projectData;
return View();
}
if (id.HasValue && (form == null || form.AllKeys.Length == 0))
{
using (DatabaseLayer db = new DatabaseLayer())
{
var timeReport = db.GetTimeReport(id.Value);
projectData = new NewTimeReportModel(timeReport);
if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
else if (form == null || form.AllKeys.Length == 0)
{
LoadDefaultSettings(projectData);
}
else
{
DateTime reportDate;
if (!DateTime.TryParse(form["date"], out reportDate))
ModelState.AddModelError("Date", "Felaktikt datum");
var projectNumbers = (from x in form.AllKeys
where x.Contains("_")
select x.Substring(x.IndexOf('_'))).Distinct();
projectData.Times = new TimeReportTimes(form["startTime"], form["endTime"], form["breakTime"], ModelState);
projectData.Date = reportDate;
if (!projectNumbers.Any())
ModelState.AddModelError("Projekt", "Inga projekt valda...");
else
{
int emptyHours = 0;
foreach (string projectNumber in projectNumbers)
{
projectData.Projects.Add(new NewTimeReportModel.Project
{
Description = form["description" + projectNumber],
Hours = null,
ProjectId = Guid.Parse(form["project" + projectNumber])
});
string hourString = form["hours" + projectNumber];
if (string.IsNullOrEmpty(hourString))
{
emptyHours++;
projectData.Projects[projectData.Projects.Count - 1].Hours = projectData.Times.WorkedHours;
}
else
{
if (!projectData.Projects[projectData.Projects.Count - 1].SetHours(hourString))
{
ModelState.AddModelError("hours_" + projectNumber, "Felaktig antal timmar");
}
}
}
if (emptyHours > 1 || (emptyHours == 0 && projectData.Projects.Sum(x => x.Hours) != projectData.Times.WorkedHours))
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar stämmer ej överrens");
}
if (projectData.Projects.Where(x => x.Hours <= 0).Any())
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar måste vara större än noll");
}
if (!string.IsNullOrEmpty(form["ReportId"]))
projectData.ReportId = Guid.Parse(form["ReportId"]);
if (ModelState.IsValid)
{
projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
ViewData["posted"] = true;
projectData = new NewTimeReportModel();
LoadDefaultSettings(projectData);
}
else if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
var missingdays = new DatabaseLayer().GetConsultantMissingDays(Constants.CurrentUser(User.Identity.Name));
if (missingdays.Count == 0)
{
ViewData["missingDays"] = "";
}
else
{
ViewBag.MissingDays = missingdays;
}
ViewData.Model = projectData;
return View();
}