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();
}
Related
I have a registration form and there is two inputs for password and password confirmation. When I enter distinct values I wanted it to show the error message as 'Passwords should match' or something. So I googled it and found out that update-package should fix this problem. Then I applied this solution in order to fix my problem, now, neither my error message shows up nor my submit button works.
My Registration View:
<div class="container-fluid">
#using (Html.BeginForm("Register", "User", FormMethod.Post, new { #class = "col-12" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal p-3 m-3 w-100 d-flex flex-column align-items-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group w-100">
<label class="form-control-label col-md-12">Kullanıcı adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.kullaniciAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.kullaniciAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Firma adı</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.firmaAdi, new { htmlAttributes = new { #class = "form-control", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.firmaAdi, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifre, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Şifre tekrar</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.sifreTekrar, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "password" } })
#Html.ValidationMessageFor(model => model.User.sifre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">E-mail</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.mail, new { htmlAttributes = new { #class = "form-control", #required = "required", #type = "text" } })
#Html.ValidationMessageFor(model => model.User.mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Telefon</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.telefon, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.User.telefon, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Ülkeniz</label>
#Html.EditorFor(model => model.Address.ulkeID, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value="Türkiye" } })
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz il</label>
<select class="form-control col-md-12" name="Address.sehirID" id="il" required></select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Bulunduğunuz ilçe</label>
<select class="form-control col-md-12" name="Address.ilceID" id="ilce" disabled required>
<option>Bir İl Seçiniz</option>
</select>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Açık adresiniz</label>
<div class="col-md-12">
#Html.EditorFor(model => model.Address.acikAdres, new { htmlAttributes = new { #class = "form-control", #type = "text", #required = "required" } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<label class="form-control-label col-md-12">Oluşturulma Tarihi</label>
<div class="col-md-12">
#Html.EditorFor(model => model.User.olusturulmaTarihi, new { htmlAttributes = new { #class = "form-control", #type = "text", #readonly="readonly", #Value=sqlFormat } })
#Html.ValidationMessageFor(model => model.Address.acikAdres, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group w-100">
<div class="col-md-offset-2 col-md-12">
<input type="submit" value="Kaydol" class="btn btn-success" />
</div>
</div>
</div>
}
</div>
Register Action:
[HttpPost]
public ActionResult Register(RegisterVM model)
{
tblKullanici user = null;
tblAdres address = null;
if(model != null)
{
db = new DatabaseContext();
user = model.User;
address = model.Address;
db.tblKullanici.Add(user);
db.tblAdres.Add(address);
db.SaveChanges();
if (db.SaveChanges() > 0)
{
Session["login"] = model.User;
return RedirectToAction("Index", "App");
}
}
ViewBag.Message = "Kayıt işlemi sırasında hata oluştu!";
return View(model);
}
jQuery
<script>
// ajax call to bring district and city info dynamically according to the city value
$(function () {
$.ajaxSetup({
type: "post",
url: "/User/IlIlce",// target
dataType: "json"
});
$.extend({
ilGetir: function () {
$.ajax({
//sending data
data: { "tip": "ilGetir" },
success: function (sonuc) {
//check result if ok then append it to selectlist
if (sonuc.ok) {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#il").append(optionhtml);
$("body").append(optionhtml);
});
}
}
});
},
ilceGetir: function (cityID) {
$.ajax({
// then we get the districts with cityID
data: { "ilID": cityID, "tip": "ilceGetir" },
success: function (sonuc) {
// deleting records
$("#ilce option").remove();
if (sonuc.ok) {
// disabled to false
$("#ilce").prop("disabled", false);
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
} else {
$.each(sonuc.text, function (index, item) {
var optionhtml = '<option value="' + item.Value + '">' + item.Text + '</option>';
$("#ilce").append(optionhtml);
});
}
}
});
}
});
// invoke ilGetir to get city values
$.ilGetir();
// on change in city value
$("#il").on("change", function () {
// we get the id of selected value
var cityID = $(this).val();
// and pass it to the ilceGetir function to get the districts
$.ilceGetir(cityID);
});
});
</script>
and the method that ajax call goes:
public JsonResult IlIlce(int? ilID, string tip)
{
db = new DatabaseContext();
List<SelectListItem> sonuc = new List<SelectListItem>();
bool isSuccessful = true;
try
{
switch (tip)
{
case "ilGetir":
// we assign the city values in db to sonuc(result) variable
foreach (var sehir in db.tblSehir.ToList())
{
sonuc.Add(new SelectListItem
{
Text = sehir.sehirAdi,
Value = sehir.sehirID.ToString()
});
}
break;
case "ilceGetir":
// we will fetch districts with sehirID(cityID)
foreach (var ilce in db.tblİlce.Where(il => il.bagliOlduguSehirID == ilID).ToList())
{
sonuc.Add(new SelectListItem
{
Text = ilce.ilceAdi,
Value = ilce.ilceID.ToString()
});
}
break;
default:
break;
}
}
catch (Exception e)
{
// if we encounter an error
isSuccessful = false;
sonuc = new List<SelectListItem>();
sonuc.Add(new SelectListItem
{
Text = e.Message,
Value = "Default"
});
}
// i return the results as json
return Json(new { ok = isSuccessful, text = sonuc });
}
ilce means: district
sehir/il both means: city
sifre: password
kullaniciAdi: username
telefon: phone number
ulke: country
ilGetir : fetch city
ilceGetir: fetch district
kullanici: user
adres: address
sonuc: result
tip: type
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 working on load more data functionality as per my requirement I am displaying 12 records for the first time and it works fine for me but whenever I am trying to show the rest data the earlier data is getting lost and the current data is displaying.
For this purpose, I am using a list which is coming from code behind but my problem is I'd declared the List on the view which is initialized each and every time then every time it becomes null on at the time of data binding that is the reason earlier data is getting lost.
For this purpose, I can not use AJAX
Here is my View
#model List<ChangiRecommends.BAL.ViewModel.Product.ProductViewModel>
#using ChangiRecommends.BAL.ViewModel.Product;
#using ChangiRecommends.Utilities;
#{
if(ViewBag.productCount > 12)
{
}
List<ProductViewModel> productList = new List<ProductViewModel>();
if(productList.Count == 0)
{
productList = Model;
}
else
{
productList.AddRange(Model);
}
ViewBag.Title = "destination";
Layout = "~/Views/Shared/_Layout.cshtml";
var key = ViewBag.Key;
var searchingKey = ViewBag.searchingkey;
var skip = ViewBag.skip;
}
<div class="destination_pics">
<div class="row">
#if (productList.Count>0)
{
int count = 0;
foreach (var item in productList)
{
if (count == 0)
{
<div class="col-sm-8">
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
</div>
}
else if (count > 0 && count <= 2)
{
if (count == 1)
{
#:<div class="col-sm-4">
}
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
if (count == 2)
{
#:</div>
<div class="clearfix"></div>
}
}
else if (count > 2 && count <= 5)
{
<div class="col-sm-4">
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
</div>
}
else if (count > 5 && count <= 8)
{
<div class="col-sm-4">
<div class="card activityBox activeBox">
<a href="#Url.Action("tourdetail","customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="dealTags">
<div class="tag-spcial">Special Offer</div>
</div>
<img class="card-img-top" src="#item.ProductImage" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.ProductDisplayName</h5>
<div class="row">
<div class="col-md-4 dealPrice">
<label>From</label>
$#item.OnlinePrice <span>$30.00</span>
</div>
<div class="col-md-5 dealLocation"><label>Location</label>#item.DestinationName</div>
<div class="col-md-3 favIt"><i class="far fa-heart"></i></div>
</div>
</div>
</a>
</div>
</div>
}
else if (count > 8 && count < 12)
{
<div class="col-sm-4">
<div class="card activityBox">
<a href="#Url.Action("tourdetail","customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="dealTags">
<div class="tag-spcial">Special Offer</div>
</div>
<img class="card-img-top" src="#item.ProductImage" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.ProductDisplayName</h5>
<div class="row">
<div class="col-md-4 dealPrice">
<label>From</label>
$#item.OnlinePrice <span>$30.00</span>
</div>
<div class="col-md-5 dealLocation"><label>Location</label>#item.DestinationName</div>
<div class="col-md-3 favIt"><i class="far fa-heart"></i></div>
</div>
</div>
</a>
</div>
</div>
}
count++;
}
if (ViewBag.productCount > 12)
{
skip += 12;
<div class="clearfix"></div>
<div class="loadMore"> Load More Results</div>
}
}
</div>
</div>
</div>
In this view, I'd declared a list on the top as it is initialized at every and I want to declare it as static so that the earlier data should not be lost.
Here is my controller.
public ActionResult destination(string key, string searchingkey, FilterDataViewModel model, int skip = 0)
{
TempData["HeaderColor"] = true;
if (!string.IsNullOrEmpty(key))
{
int destinationId = QueryStringManager.Decrypt(key);
var destinationInfo = _masterRepo.GetMasterDataByID(destinationId);
var productList = _websiteRepo.GetAllProductListByDestinationId(destinationId).OrderByDescending(x => x.DestinationWeightPriority).ToList();
if (model.DestinationCityID > 0)
{
productList = (from prod in productList where prod.DestinationCity == model.DestinationCityID select prod).ToList();
}
ViewBag.productCount = productList.Count();
var a = productList.Skip(skip).Take(12).ToList();
ViewBag.ProductList = productList.Skip(skip).Take(12).ToList();
var allAdbyDestination = _websiteRepo.GetAllAdvertisementList(destinationId);
ViewBag.allDestinationAd = allAdbyDestination;
ViewBag.DestinationName = destinationInfo.MasterData;
ViewBag.DestinationImages = destinationInfo.ImagePath;
var categoryID = MasterConstant.GetCategoryID(CatergoryConstant.City);
var allDestinationCity = _masterRepo.GetMasterDataByCategoryIDandXrefID(categoryID, destinationId);
ViewBag.DestinationCityList = new SelectList(allDestinationCity, "ItemID", "MasterData");
ViewBag.Key = key;
ViewBag.searchingkey = searchingkey;
ViewBag.skip = skip;
return View(a);
}
else
{
return RedirectToAction("index", "home");
}
}
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"})
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.