Routes not working always coming back to the same page - c#

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");
}

Related

How to pass external object list and form object in ajax to mvc controller

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>

CaptchaMvc.Mvc5 does not refresh partial view

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

Attach Multiple Files in ASP.NET MVC

I've been trying to attach/upload multiple files in the website I'm making. The Name, Email, Subject & Message are sending but there's no attachment in the message. It seems that the files don't get in the uploads folder. I really don't know what's wrong. Please help me. I'm new with this kind of stuff. Thank you. Here's my view:
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName)
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject)
</div>
<div class="col-md-12">
#using (Html.BeginForm("Multiple", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="multiple">
<input type="file" class="multiple" name="files" multiple />
</div>
<div id="single">
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
</div>
}
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message)
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
And here's my controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model)
{
if (ModelState.IsValid)
{
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if(IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
//return RedirectToAction("Sent");
ViewBag.Message = "Your message has been sent!";
//TempData["message"] = "Message sent";
ModelState.Clear();
return View("Index");
}
}else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
[HttpPost]
public ActionResult Multiple(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
}
}
return View();
}
Your first row of code is the problem.
Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data"
That is a Post action to Index of your home controller. It is not possible to HttpPost another HttpPost, the action itself is expecting an HttpPost, as you can see by the data annotation above the ActionResult name
Why do you use nested forms?
Your view should not be contained nested form submissions. so reduce it to one and the same can be use to upload files.
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName)
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject)
</div>
<div class="col-md-12">
{
<div id="multiple">
<input type="file" class="multiple" name="files" multiple />
</div>
<div id="single">
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
<input type="file" class="single" name="files" /><br />
</div>
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message)
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}
Moreever add a parameter to Action to receive files from client request and process it at same action.
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
//logic here upload file logic here.
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(Path.Combine(Server.MapPath("/uploads"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
}
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if(IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
var message = new MailMessage();
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
//return RedirectToAction("Sent");
ViewBag.Message = "Your message has been sent!";
//TempData["message"] = "Message sent";
ModelState.Clear();
return View("Index");
}
}else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}

Uploadify in ASP.NET MVC

I would like to put uploadify in the website I'm making so that I can see the progress of the files that being attach. So I search on how to do that, I know I'm doing something wrong that's why it's not working(the progress doesn't show). Please help me, I'm new with this kind of stuff. Thank you. Here's my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailFormModel model, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
List<string> paths = new List<string>();
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
paths.Add(path);
}
}
var message = new MailMessage();
foreach (var path in paths)
{
var fileInfo = new FileInfo(path);
var memoryStream = new MemoryStream();
using (var stream = fileInfo.OpenRead())
{
stream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
string fileName = fileInfo.Name;
message.Attachments.Add(new Attachment(memoryStream, fileName));
}
//Rest of business logic here
string EncodedResponse = Request.Form["g-Recaptcha-Response"];
bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
if (IsCaptchaValid)
{
var body = "<p>Email From: {0} ({1})</p><p>Subject: {2} </p><p>Message:</p><p>{3}</p>";
message.To.Add(new MailAddress("***#gmail.com")); // replace with valid value
message.From = new MailAddress("***#ymailcom"); // replace with valid value
message.Subject = "Your email subject";
message.Body = string.Format(body, model.FromName, model.FromEmail, model.FromSubject, model.Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
var credential = new NetworkCredential
{
UserName = "***#gmail.com", // replace with valid value
Password = "***" // replace with valid value
};
smtp.Credentials = credential;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
ViewBag.Message = "Your message has been sent!";
ModelState.Clear();
return View("Index");
}
}
else
{
TempData["recaptcha"] = "Please verify that you are not a robot!";
}
}
return View(model);
}
public ActionResult Upload()
{
var file = Request.Files["Filedata"];
string savePath = Server.MapPath(("~/uploads") + file.FileName);
file.SaveAs(savePath);
return Content(Url.Content(("~/uploads") + file.FileName));
}
And here's the script that I add to my _Layout.cshtml :
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Content/UploadifyContent/jquery.uploadify.min.js")"></script>
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/UploadifyContent/uploadify.css")" />
<script type="text/javascript">
$(function () {
$('#file_upload').uploadify({
'swf': "#Url.Content("~/Content/UploadifyContent/uploadify.swf")",
'cancelImg': "#Url.Content("~/Content/UploadifyContent/uploadify-cancel.png")",
'uploader': "#Url.Action("Upload", "Home")",
'onUploadSuccess': function (file, data, response) {
$("#uploaded").append("<img src='" + data + "' alt='Uploaded Image' />");
}
});
});
</script>
And here's my view:
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-4">
<div class="contact_form block">
<div class="row">
<div class="col-md-12 col-sm-12">
<div id="note"></div>
</div>
</div>
<div id="fields">
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromEmail, null, new { #class = "text-danger" })
</div>
<div class="clear"></div>
<div class="col-md-12 col-sm-6">
#Html.LabelFor(m => m.FromSubject)
#Html.TextBoxFor(m => m.FromSubject, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromSubject, null, new { #class = "text-danger" })
</div>
<div class="col-md-12 col-sm-6">
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Attachments</label>
<input type="file" name="files" id="file1" multiple />
</form>
<div id="uploaded"></div>
</div>
<div class="col-md-12">
#Html.LabelFor(m => m.Message)
#Html.TextAreaFor(m => m.Message, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Message, null, new { #class = "text-danger" })
</div>
<div class="col-md-12">
<div>
#if ((TempData["recaptcha"]) != null)
{
<p>#TempData["recaptcha"]</p>
}
</div>
<div class="g-recaptcha" data-sitekey="6LfVHx8TAAAAAMTDxxQrHDCxO1SyXf1GgbgNBZ5a"></div>
</div>
<div class="col-md-12"><input class="shortcode_button" type="submit" value="Send"></div>
</div>
</div>
</div>
}

Logout doesnot return to the proper view

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.

Categories

Resources