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.
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 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
Controller
public ActionResult Isearch( string OFFICE_TYPE,string DEPARTMENT, string FILECATEGORY,string fromdate,string todate)
{
ViewBag.officetype = new SelectList(entity.TBL_OFFICETYPE.ToList(), "OFID", "OFFICE_TYPE");
//var list = new SelectList(entity.TBL_OFFICETYPE.Select(r => r.OFFICE_TYPE).ToList());
var list2 = new SelectList(entity.TBL_DEPARTMENT.Select(r => r.DEPARTMENTCODE).ToList());
ViewBag.department = list2;
var list4 = new SelectList(entity.TBL_FILECATEGORY.ToList(), "FILECATEGORY", "FILECATEGORY");
ViewBag.filecategory = list4;
var myinboxdata = entity.TBL_INBOX.ToList();
//var myinboxs = from res in entity.TBL_INBOX
// select new { res.OFFICETYPE, res.DEPARTMENTCODE, res.DESCRIPTION };
var myinbox1=from s in entity.TBL_INBOX select s;
if (String.IsNullOrEmpty(fromdate)&& String.IsNullOrEmpty(todate))
{
//DateTime fdate = Convert.ToDateTime(fromdate).Date;
//DateTime tdate = Convert.ToDateTime(todate).Date;
myinbox1 = entity.TBL_INBOX.Where(s => s.OFFICETYPE.Contains(OFFICE_TYPE) && s.DEPARTMENTCODE.Contains(DEPARTMENT) && s.FILECATEGORY.Contains(FILECATEGORY));
}
else
{
myinbox1 = entity.TBL_INBOX.Where(s => s.OFFICETYPE.Contains(OFFICE_TYPE) && s.DEPARTMENTCODE.Contains(DEPARTMENT) && s.FILECATEGORY.Contains(FILECATEGORY) && (s.UDATE >= Convert.ToDateTime(fromdate).Date && s.UDATE <= Convert.ToDateTime(todate)));
}
var data = myinbox1.OrderBy(x => x.OFFICETYPE).GroupBy(x => new { x.OFFICETYPE, x.DEPARTMENTCODE, x.DESCRIPTION }).Select(g => new { g.Key.OFFICETYPE, g.Key.DEPARTMENTCODE, g.Key.DESCRIPTION, Unread = g.Count() });
List<Inbox> mydata = new List<Models.Inbox>();
foreach (var myinbox in data)
{
mydata.Add(new Models.Inbox { OType = myinbox.OFFICETYPE, DCode = myinbox.DEPARTMENTCODE, Desc = myinbox.DESCRIPTION, Unread = myinbox.Unread });
}
ViewBag.data = mydata.ToList();
return View("Inbox");
}`enter code here`
In thee above code i passing the data from view. While passing the data i am getting the key for office type and department. Instead i want to get their value(text)
View
#using (Html.BeginForm("Isearch", "Transactions", FormMethod.Post))
{
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">My InBox</h3>
</div>
<div class="panel-body">
<div class="col-md-12 col-sm-12">
<div class="form-group col-md-4 col-sm-4">
<label for="Office">OfficeType</label>
#*#Html.DropDownList("officetype", ViewBag.officetype as SelectList, new { #class = "form-control input-sm", #id = "name" })*#
#Html.DropDownList("OFFICE_TYPE", ViewBag.officetype as SelectList, new { #class = "form-control input-sm", #id = "Office",name="Office" })
</div>
<div class="form-group col-md-4 col-sm-4" id="depart">
<label for="DEPARTMENT">Department</label>
#*#Html.DropDownList( ViewBag.Department,Enumerable.Empty<SelectListItem>(), new { #class = "form-control input-sm"})*#,
<select id="DEPARTMENT" name="DEPARTMENT" class = "form-control input-sm" ></select>
</div>
<div class="form-group col-md-4 col-sm-4">
<label for="FILECATEGORY">FILECATEGORY </label>
#Html.DropDownList("FILECATEGORY", ViewBag.filecategory as SelectList, new { #class = "form-control input-sm", #id = "name" })
</div>
<div class="form-group col-md-4 col-sm-4">
<label>From Date</label>
#Html.TextBox("fromdate", null, new { #id = "fromdate", #class = "form-control input-sm" })
#*<input name="fdate" type="text" id="fromdate" class="form-control input-sm" />*#
</div>
<div class="form-group col-md-4 col-sm-4">
<label>To Date</label>
#Html.TextBox("todate", null, new { #id = "todate", #class = "form-control input-sm" })
#*<input type="text" id="todate" class="form-control input-sm" />*#
</div>
<div class="form-group col-md-4 col-sm-4">
<br />
<input type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
the above code is view code where i an passing the value through the id and name property.
In thee above code i passing the data from view. While passing the data i am getting the key for office type and department. Instead i want to get their value(text)
Giving you an example:
<select id="drpgenderid" name="drpgendername">
<option value="1">#Html.Label("FEMALE",Model.gender, new { #style = "", #id = "new_id_gender", #name = "name_new_gender", #placeholder = "Gender", #enabled = "false", #value = "FEMALE" })</option>
<option selected="selected" value="2">#Html.Label("MALE",Model.gender, new { #style = "", #id = "new_id_gender", #name = "name_new_gender", #placeholder = "Gender", #enabled = "false", #value = "MALE" })</option>
</select>
SCRIPT
function GetData()
{
var pdrp = document.getElementById("drpgenderid");
gender = pdrp.options[pdrp.selectedIndex].value;
}
using AJAX
GetData();
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
url: "#Url.Action("GetDemoData")",
data: "{'gender':'" + gender.trim() + "'}",
success: function (data) {
}
});
CONTROLLER
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetDemoData(String gender)
{
string gtGender = gender;
}
use ViewBag and #Html.DropDownList we can do drop-down without using model data
In controller
public ActionResult dropdown() {
var customers = new List<Customer>();
customers.Add(new Customer { Name = "Airi Satou", ID = 1 });
customers.Add(new Customer { Name = "Brenden Wagner", ID = 2 });
customers.Add(new Customer { Name = "Brielle Williamson", ID = 2 });
ViewBag.DropData = customers;
return View();
}
In View
#Html.DropDownList("CustomerDropDown", new SelectList(ViewBag.DropData, "ID", "Name"), new { #class="form-control"})
#Html.DropDownList("CustomerDropDown2", new SelectList(ViewBag.DropData, "Name", "Name"), new { #class="form-control"})
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();
}