I need to clear filter after search
Here is my index.cshtml
<form method="post" id="form">
<div class="row">
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchNom" value="#ViewData["sNom"]?.ToString()" class="form-control" id="nom" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchPrenom" value="#ViewData["sPrenom"]?.ToString()" id="prenom" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchEmail" value="#ViewData["sEmail"]?.ToString()" id="email" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="search" name="searchTelephone" value="#ViewData["sTelephone"]?.ToString()" id="telephone" />
</div>
</div>
<div class="col-md-2">
<p>
<input type="submit" value="Search" class="btn btn-primary" />
<button class="btn" type="reset" id="reset" onclick="Reset()"><i class="fa fa-trash"></i></button>
</p>
</div>
</div>
</form>
and then the action Index:
public string searchNom { get; set; }
public string searchPrenom { get; set; }
public string searchEmail { get; set; }
public string searchTelephone { get; set; }
public async Task<IActionResult> Index(string searchNom, string searchPrenom, string searchEmail, string searchTelephone, int? pageNumber, string currentFilter)
{
if (searchNom != null || searchPrenom != null || searchEmail != null || searchTelephone != null)
{
pageNumber = 1;
}
var personnels = from s in _context.personnels
select s;
if (!String.IsNullOrEmpty(searchNom) || !String.IsNullOrEmpty(searchPrenom) || !String.IsNullOrEmpty(searchEmail) || !String.IsNullOrEmpty(searchTelephone))
{
personnels = personnels.Where(s => s.Nom.Equals(searchNom) || s.Prenom.Equals(searchPrenom) || s.Email.Equals(searchEmail) || s.Telephone.Equals(searchTelephone));
ViewData["sNom"] = searchNom ;
ViewData["sPrenom"] = searchPrenom;
ViewData["sEmail"] = searchEmail;
ViewData["sTelephone"] =searchTelephone ;
}
else
{
ViewData["sNom"] = "";
ViewData["sPrenom"] = "";
ViewData["sEmail"] = "";
ViewData["sTelephone"] = "";
}
int pageSize = 20;
return View(await Pagination<PersonnelModel>.CreateAsync(personnels.AsNoTracking(), pageNumber ?? 1, pageSize));
}
js code:
<script>
function Reset() {
document.getElementById("nom").value = "";
document.getElementById("prenom").value = "";
document.getElementById("email").value = "";
document.getElementById("telephone").value = "";
}</script>
Now the problem ,the button reset dosen't work ther is an exception Uncaught TypeError: Cannot set property 'selectedIndex' of null
at Reset ((index):357)
at HTMLButtonElement.onclick ((index):107)
Is there any way how to make "reset" button working on form data values in same time please?
Thank you very much in advance for any kind of help.
Welcome to SO.
The code above can't be executed as we don't have the _context variable, nor the PersonelModel class.
The way you use ViewData to initially populate the form seems a little shady - I'd make sure I pass the view model instead. I appreciate that this is not the issue here.
Answering the actual question, I'd start with wrapping the script functions with
document.addEventListener("DOMContentLoaded", function(){
// Handler when the DOM is fully loaded
});
or have a look here
Instead of depending on onclick attribute, have a look at .click() function from jQuery library, have a look here
Using the above, your code will look something like:
$("#submit-button").click(function() {
document.getElementById("nom").value = "";
document.getElementById("prenom").value = "";
document.getElementById("email").value = "";
document.getElementById("telephone").value = "";
});
given you added submit-button id to your button.
I found the solution finally ,i added this document.forms["form"].submit(); also
<script>
function Reset() {
document.getElementById("nom").value = "";
document.getElementById("prenom").value = "";
document.getElementById("email").value = "";
document.getElementById("telephone").value = "";
document.forms["form"].submit();
}</script>
Related
So I am having this extremely bizarre issue where the my model is coming back as null after submitting my form.
Now I understand that a model coming back null is not necessarily bizarre on its own, but what makes it extremely bizarre is that it only happens on very specific conditions:
When the application has been deployed to my on-premise IIS server
When I have first modified the date filters for my data
I cannot for the life of me figure out why this is happening since when I run on local, everything works fine. But once I deploy on the on-prem server, and I modify my date filters for the page I start getting this error.
Here is my view:
#model CoFCrimeBulletin.Models.ViewModels.CallsForServiceViewModel
#{
ViewData["Title"] = "Calls For Service";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div style="margin-left: 400px; width: 100%">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Arrests">Arrests</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Warrants">Warrants</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="StreetChecks">Street Checks</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark active" asp-area="" asp-controller="Home" asp-action="CallsForService">Calls For Service</a>
</li>
</ul>
</div>
<div class="container pt-5 CallsForService" >
<form asp-controller="Home" asp-action="CallsForService" method="post">
<div class=row>
<div class="pr-2">
<label><b>Search: </b></label>
<input type="text" id="WarrantsSearch" onkeyup="myWarrantsFunction()" placeholder="Search Calls for Service">
</div>
<div class="pr-2">
<label><b>Start Date: </b></label>
<input id="CallsForServiceStartDate" type="date" asp-for="#Model.StartDate" class="text-box single-line" value="#Model.StartDate.ToString("yyyy-MM-dd")" />
</div>
<div class="pr-2">
<label><b>End Date: </b></label>
<input id="CallsForServiceEndDate" type="date" asp-for="#Model.EndDate" class="text-box single-line" value="#Model.EndDate.ToString("yyyy-MM-dd")" />
</div>
<div>
<button type="submit" class="btn btn-secondary" onclick="VerifyDates()">Go</button>
</div>
</div>
</form>
<div class="row ">
<div class="col-sm-4 tableheading"><b>LOCAL CRIME</b></div>
</div>
<div class="row details">
<div class="col-sm" style="text-align:center"><b>Details</b></div>
</div>
<form asp-controller="Home" asp-action="CreatePDF" method="post">
<div id="LocalCrimeTable">
#{
for (int i = 0; i < Model.callsForService.Count; i++)
{
<div class="row suspectName">
<div class="col-sm-9">
<b>#Model.callsForService[i].type - #Model.callsForService[i].location</b>
<input asp-for="#Model.callsForService[i].location" style="display:none;" value="#Model.callsForService[i].location">
<input asp-for="#Model.callsForService[i].type" style="display:none;" value="#Model.callsForService[i].type">
</div>
<div class="col-sm-3" style="text-align:right">
<b>#Model.callsForService[i].datetime</b>
<input type="date" asp-for="#Model.callsForService[i].datetime" style="display:none;" value="#Model.callsForService[i].datetime.ToString("yyyy-MM-dd")">
</div>
</div>
<div class="row rmsNumber">
<div class="col-sm-4">
<b>#Model.callsForService[i].rmsnumdisplay</b>
<input asp-for="#Model.callsForService[i].rmsnumdisplay" style="display:none;" value="#Model.callsForService[i].rmsnumdisplay">
<input asp-for="#Model.callsForService[i].rmsnum" style="display:none;" value="#Model.callsForService[i].rmsnum">
</div>
<div class="col-sm-4">
<b>#Model.callsForService[i].zone</b>
<input asp-for="#Model.callsForService[i].zone" style="display:none;" value="#Model.callsForService[i].zone">
</div>
<div class="col-sm-4">
<b>COMPLAINTANT:</b> #Model.callsForService[i].caller
<input asp-for="#Model.callsForService[i].caller" style="display:none;" value="#Model.callsForService[i].caller">
</div>
</div>
<div class="row">
<div class="col-sm">
<b>REMARKS:</b> #Model.callsForService[i].remarks
<input asp-for="#Model.callsForService[i].remarks" style="display:none;" value="#Model.callsForService[i].remarks">
</div>
</div>
<div class="row">
<div class="col-sm">
<b>CLEAR REMARKS:</b> #Model.callsForService[i].clearremarks
<input asp-for="#Model.callsForService[i].clearremarks" style="display:none;" value="#Model.callsForService[i].clearremarks">
</div>
</div>
if(Model.IsWriter)
{
<div id="td">
+
</div>
}
<div class="row">
<div class="col-12"> <b>ADDITIONAL NOTES:</b>
#if(Model.callsForService[i].additionalnotes != null && Model.callsForService[i].additionalnotes != ""){
<p class="truncateCrime">#Model.callsForService[i].additionalnotes</p>
<a class="expandNotesCrime underline text-green-500 button" href="#">Read more...</a>
<a class="shrinkNotesCrime underline text-green-500 button" href="#" style="display:none">Read less...</a>
}
<input asp-for="#Model.callsForService[i].additionalnotes" style="display:none;" value="#Model.callsForService[i].additionalnotes">
</div>
</div>
<div class="row" style="text-transform:capitalize">
<input asp-for="#Model.callsForService[i].createPDF" type="checkbox"> Check to Include in PDF
</div>
}
<input type="date" asp-for="#Model.StartDate" style="display:none;" value="#Model.StartDate.ToString("yyyy-MM-dd")">
<input type="date" asp-for="#Model.EndDate" style="display:none;" value="#Model.EndDate.ToString("yyyy-MM-dd")">
<input asp-for="#Model.SourcePage" style="display:none;" value="#Model.SourcePage">
}
</div>
#{
<input type="submit" class="btn btn-primary mt-5" value="Create PDF">
}
</form>
</div>
And my Controller:
using CoFCrimeBulletin.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
namespace CoFCrimeBulletin.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
private bool IsWriter()
{
bool localtest = false;
if (localtest) { return true; }
else
{
//ClaimsIdentity userIdentity = (ClaimsIdentity)User.Identity;
var UI = (ClaimsIdentity)User.Identity;
List<string> Groups = new List<string>();
if (UI.Claims.Where(c => c.Type == "groups").Count() > 0)
{
foreach (var group in UI.Claims.Where(c => c.Type == "groups"))
{
Groups.Add(group.Value);
}
}
return Groups.Contains("f615ae09-b313-444a-a41c-5dc2d586fc03");
}
}
public IActionResult Index(Models.ViewModels.BaseViewModel model)
{
Models.ViewModels.HomePageViewModel myModel = new Models.ViewModels.HomePageViewModel();
Repository.WarrantRepository warrantRepository = new Repository.WarrantRepository(_configuration);
Repository.ArrestRepository arrestRepository = new Repository.ArrestRepository(_configuration);
Repository.CrimeRepository crimeRepository = new Repository.CrimeRepository(_configuration);
DateTime startDate = model.StartDate;
DateTime endDate = model.EndDate;
myModel.warrants = warrantRepository.GetWarrants(startDate, endDate);
myModel.arrests = arrestRepository.GetArrests(startDate, endDate);
myModel.streetChecks = crimeRepository.GetStreetChecks(startDate, endDate);
myModel.callsForService = crimeRepository.GetCallsForService(startDate, endDate);
myModel.StartDate = startDate == DateTime.MinValue ? DateTime.Now.AddDays(-1) : startDate;
myModel.EndDate = endDate == DateTime.MinValue ? DateTime.Now : endDate;
myModel.IsWriter = IsWriter();
myModel.SourcePage = "Index";
return View(myModel);
}
public IActionResult Warrants(Models.ViewModels.BaseViewModel model)
{
DateTime startDate = model.StartDate;
DateTime endDate = model.EndDate;
Models.ViewModels.WarrantViewModel myModel = new Models.ViewModels.WarrantViewModel();
myModel.StartDate = startDate == DateTime.MinValue ? DateTime.Now.AddDays(-1) : startDate;
myModel.EndDate = endDate == DateTime.MinValue ? DateTime.Now : endDate;
Repository.WarrantRepository warrantRepository = new Repository.WarrantRepository(_configuration);
myModel.Warrants = warrantRepository.GetWarrants(startDate, endDate);
myModel.IsWriter = IsWriter();
myModel.SourcePage = "Warrants";
return View(myModel);
}
public IActionResult Arrests(Models.ViewModels.BaseViewModel model)
{
DateTime startDate = model.StartDate;
DateTime endDate = model.EndDate;
Models.ViewModels.ArrestViewModel myModel = new Models.ViewModels.ArrestViewModel();
myModel.StartDate = startDate == DateTime.MinValue ? DateTime.Now.AddDays(-1) : startDate;
myModel.EndDate = endDate == DateTime.MinValue ? DateTime.Now : endDate;
Repository.ArrestRepository arrestRepository = new Repository.ArrestRepository(_configuration);
myModel.arrests = arrestRepository.GetArrests(startDate, endDate);
myModel.IsWriter = IsWriter();
myModel.SourcePage = "Arrests";
return View(myModel);
}
public IActionResult StreetChecks(Models.ViewModels.BaseViewModel model)
{
DateTime startDate = model.StartDate;
DateTime endDate = model.EndDate;
Models.ViewModels.StreetChecksViewModel myModel = new Models.ViewModels.StreetChecksViewModel();
myModel.StartDate = startDate == DateTime.MinValue ? DateTime.Now.AddDays(-1) : startDate;
myModel.EndDate = endDate == DateTime.MinValue ? DateTime.Now : endDate;
Repository.CrimeRepository crimeRepository = new Repository.CrimeRepository(_configuration);
myModel.streetChecks = crimeRepository.GetStreetChecks(startDate, endDate);
myModel.IsWriter = IsWriter();
myModel.SourcePage = "StreetChecks";
return View(myModel);
}
public IActionResult CallsForService(Models.ViewModels.BaseViewModel model)
{
DateTime startDate = model.StartDate;
DateTime endDate = model.EndDate;
Models.ViewModels.CallsForServiceViewModel myModel = new Models.ViewModels.CallsForServiceViewModel();
myModel.StartDate = startDate == DateTime.MinValue ? DateTime.Now.AddDays(-1) : startDate;
myModel.EndDate = endDate == DateTime.MinValue ? DateTime.Now : endDate;
Repository.CrimeRepository crimeRepository = new Repository.CrimeRepository(_configuration);
myModel.callsForService = crimeRepository.GetCallsForService(startDate, endDate);
myModel.IsWriter = IsWriter();
myModel.SourcePage = "CallsForService";
return View(myModel);
}
public IActionResult AddAdditionalNote(Models.ViewModels.AdditionalInfoViewModel model)
{
try
{
Repository.AdditionalNotesRepository additionalNotesRepository = new Repository.AdditionalNotesRepository(_configuration);
string redirectAction = Helpers.AdditionalInfoHelper.GetRedirectActionName(model.sourcePage);
Models.ViewModels.BaseViewModel myModel = new Models.ViewModels.BaseViewModel();
string rmsNum = model.rmsNum.Replace("-", string.Empty);
string remarks = model.additionalNotes == null? "" : model.additionalNotes;
myModel.StartDate = model.StartDate;
myModel.EndDate = model.EndDate;
additionalNotesRepository.InsertAdditionalNotes(rmsNum, remarks);
return RedirectToAction(redirectAction, myModel);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return Redirect(HttpContext.Request.Headers["Referer"]);
}
public PartialViewResult RenderAdditionalInfoModal(string RmsNum, DateTime StartDate, DateTime EndDate, string SourcePage)
{
string rms = RmsNum.Replace("-", string.Empty);
Repository.AdditionalNotesRepository additionalNotesRepository = new Repository.AdditionalNotesRepository(_configuration);
Models.ViewModels.AdditionalInfoViewModel myModel = new Models.ViewModels.AdditionalInfoViewModel();
myModel.rmsNum = RmsNum;
myModel.StartDate = StartDate;
myModel.EndDate = EndDate;
myModel.sourcePage = SourcePage;
myModel.additionalNotes = additionalNotesRepository.GetAdditionalNote(rms);
return PartialView("_AdditionalInfoPartial", myModel);
}
[HttpPost]
public IActionResult CreatePDF(Models.ViewModels.HomePageViewModel model)
{
try
{
Models.ViewModels.BaseViewModel myModel = new Models.ViewModels.BaseViewModel();
Models.PdfCreation pdf = new Models.PdfCreation();
string redirectAction = model.SourcePage;
redirectAction = Helpers.AdditionalInfoHelper.GetRedirectActionName(model.SourcePage);
myModel.StartDate = model.StartDate;
myModel.EndDate = model.EndDate;
pdf.arrests = Helpers.PdfHelper.GetArrestsForPdfCreation(model.arrests);
pdf.warrants = Helpers.PdfHelper.GetWarrantsForPdfCreation(model.warrants);
pdf.callsForService = Helpers.PdfHelper.GetCallsForServiceForPdfCreation(model.callsForService);
pdf.streetChecks = Helpers.PdfHelper.GetStreetChecksForPdfCreation(model.streetChecks);
Helpers.PdfHelper.CreatePdf(pdf);
return RedirectToAction(redirectAction, myModel);
}
catch (Exception ex)
{
using (StreamWriter writer = new StreamWriter(#"C:\CrimeBulletin PDFs\out.txt", true))
{
Console.SetOut(writer);
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
return Redirect(HttpContext.Request.Headers["Referer"]);
}
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult Privacy()
{
return View();
}
}
}
And Models:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoFCrimeBulletin.Models.ViewModels
{
public class HomePageViewModel : BaseViewModel
{
public List<Arrest> arrests { get; set; }
public List<Warrant> warrants { get; set; }
public List<Crime> callsForService { get; set; }
public List<Crime> streetChecks { get; set; }
public HomePageViewModel()
{
arrests = new List<Arrest>();
warrants = new List<Warrant>();
callsForService = new List<Crime>();
streetChecks = new List<Crime>();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace CoFCrimeBulletin.Models.ViewModels
{
public class CallsForServiceViewModel : BaseViewModel
{
public List<Crime> callsForService { get; set; }
public CallsForServiceViewModel()
{
callsForService = new List<Crime>();
}
}
}
And a screen shot showing the model is null when I submit the form:
Null model
And a screen shot showing that the model is in fact populating if I don't modify the date filters:
Populated model
Its important to note that both these screenshots are showing the results of the same form being submitted. Also want to point out that these screen shots are taken from remote debug on the server. Not from my local machine.
Also important to note that when I run this on my local machine, I can submit any way I want including after modifying the date filters and I never get a null model back. I have only been able to replicate this error when the app is deployed to my on-prem IIS server.
I have not been able to find any other posts that match the issues I am having. Any help at all would be appreciated.
Since I am posting back all of the data shown on screen to my controller then sorting from there, could the issue be that the model is null when too much data is being posted to the controller model? Currently looking into this.
Ok I found and resolved the issue. It had nothing to do with being deployed to the on-premise IIS server or the fact that I was changing the date range and everything to do with the size of the dataset that I was posting back to the controller.
Since I am posting back all of my data back to my controller then sorting based the checkbox value, the amount of data sent back to my controller was exceeding the default limits set by asp.net core MVC.
Now as one might guess ,I was working with a small enough dataset on my local as to not exceed the limit. Furthermore, increasing the date-range of my filter would have the secondary effect of making the dataset larger.
SOLUTION:
The reason I had so much trouble identifying this error is because I was only getting nullReference errors and wasn't getting "InvalidDataException: Form value count limit 1024 exceeded."
Which, once I identified the issue brought me to this thread which informed me you can override the default limit with this bit of code:
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
});
in the ConfigureServices method in Startup.cs
I added that bit of code and the isssue went away. The model is now properly binding with large sets of data.
This question already has an answer here:
Get ID and Value from a checkbox: Return to model and use in method to insert into sql database
(1 answer)
Closed 1 year ago.
I'm trying to add values to a cross table, where the ID of a garage and a value based on a list of choices gets inserted to the database. The list looks like following in the view:
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Claim</label>
<input type="checkbox" class="checkbclass" name="Claim" id="Claim" placeholder="Claim" required="" />
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Scheduled Service</label>
<input type="checkbox" class="checkbclass" name="Scheduled" id="Scheduled" placeholder="Scheduled" required="" />
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<label class="ab">Tires</label>
<input type="checkbox" class="checkbclass" name="Tires" id="Tires" placeholder="Tires" required="" />
</div>
</div>
So 3 checkboxes is shown in the view. Here the user is supposed to choice one or more options when they edit a garage. The cross table looks like following:
[ID]
,[GarageID]
,[RequestProperty]
,[CreatedDate]
,[CreatedBy]
,[UpdatedDate]
,[UpdatedBy]
I would like to do something similar to this in SQL stored procedure:
INSERT INTO GarageCrossRequestType
(GarageID, RequestProperty)
VALUES (#GarageID, #RequestType)
Which could look something similar to:
var cmd1 = new SqlCommand("spGarageGetRequestTypes", Connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd1.Parameters.AddWithValue("#RequestType", model.requestId);
int result = cmd1.ExecuteNonQuery();
if (result == 1)
valid = true;
In the method. (To insert the garageID and the RequestTypeID.)
The Request-types can be as following:
public int Claim { get; set; } = 1;
public int ScheduledService { get; set; } = 2;
public int Tires { get; set; } = 3;
So for example, if a user choose Claim, I would like to update the table with the GarageID and Claim -> which ID would be 1. I'm sort of new to working with views, so I'm not sure how I would connect the input types to the model. So the problems are as following:
Connect the input types to the model, giving them their correct value (ex. Claim -> 1, Scheduled -> 2 etcetera) and,
My database table only accept garageId and requestType, and therefore when sending for example garageId: 4, I would need the input type Claim or whatever checkbox is choosen to only send their value (1, 2 or 3) to the database.
Anyone got a solution for this? Also I hope this makes sense, let me know otherwise and i'll try to formulate it differently.
UPDATE:
So I should have explained better from the beginning. But here's the rest of the code. So basically, there's a function where a user can Edit a garage where I would like to make it possible for them to also choose either claim/service or tires. So I would like to expand this method, and when a user selects a garage this is when they also can choose claim etcetera (It's also from this method the garageId comes from).
In the view (for edit garage):
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Garage</label>
<input type="text" class="col-lg-10 form-control" name="GarageName" id="GarageName" placeholder="Name" required="" />
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Contact person</label>
<input type="text" class="col-lg-10 form-control" name="ContactPerson" id="ContactPerson" placeholder="ContactPerson" required="" />
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-xs-2 control-label">Email</label>
<input type="email" class="col-lg-10 form-control" name="Email" id="Email" placeholder="Email" required="" onblur="validateEmail(this.value);" /><p id="InvalidMeg" style="font-size: 25px; color: red">Invalid e-mail address</p>
</div>
</div>
<button class="btn btn-md btn-primary custom" type="submit" id="saveNewGarageBtn"><i class="glyphicon glyphicon-lock"></i> Save</button>
<button class="btn btn-md btn-primary custom" type="submit" id="EditGarageBtn"><i class="glyphicon glyphicon-lock"></i> Save edit</button>
Javascript:
function editGarage(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var garageId = dataItem.GarageId;
countryId = dataItem.CountryId;
name = dataItem.Name;
var contactperson = dataItem.ContactPerson;
var email = dataItem.Email;
if (garageId != 0) {
$("#EditGarageBtn").show();
$("#saveNewGarageBtn").hide();
$("#GarageName").val(name);
$("#Country").val(countryId);
$("#ContactPerson").val(contactperson);
$("#Email").val(email);
$("#garageId").val(garageId);
}
}
Edit-garage button:
$("#EditGarageBtn").click(function () {
var customerNumber = customerNumberOfEditingGarage;
name = $("#GarageName").val();
countryId = $("#Country").val();
var garageId = $("#garageId").val();
var contactperson = $("#ContactPerson").val();
var email = $("#Email").val();
$("#EditGarageBtn").hide();
if (countryId == "Norway")
countryId = 2;
if (countryId == "Finland")
countryId = 4;
if (name.length > 0 && email.length > 0 && phone.length > 0 && contactperson.length > 0) {
$.ajax({
url: '#Url.Action("EditGarage", "Garage")',
dataType: 'JSON',
data: {
name: name, countryId: countryId, garageId: garageId,
contactperson: contactperson,
phone: phone, email: email
},
success: function (data) {
if (data == "Failure") {
toastr["error"]("Error editing Garage");
}
else {
toastr["success"]("Garage successfully updated");
customerNumberOfEditingGarage = null;
refreshGrid();
}
},
error: function () {
}
});
} else {
toastr["error"]("Error editing Garage");
}
});
Method:
public bool EditGarage(GarageModel model)
{
var valid = false;
var cmd = new SqlCommand("spGarageEditGarage", Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#GarageId", model.GarageId);
cmd.Parameters.AddWithValue("#CountryId", model.CountryId);
cmd.Parameters.AddWithValue("#ContactPerson", model.ContactPerson);
cmd.Parameters.AddWithValue("#Email", model.Email);
try
{
int result = cmd.ExecuteNonQuery();
if (result == 1)
valid = true;
}
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
Connection.Close();
}
return valid;
}
Hopefully, this became a bit clearer.
I do not know what your model is and where model.GarageId comes from. If you complete the part I did not understand, you can use the following code for model.requestId.
note: Use a radiobutton instead of a checkbox.
change view to :
#using (Html.BeginForm("YourAction", "YourController", FormMethod.Post))
{
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="radio" id="Claim" name="requestType" value="Claim">
<label for="Claim">Claim</label>
< </div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="radio" id="ScheduledService" name="requestType" value="ScheduledService">
<label for="ScheduledService">ScheduledService</label>
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="radio" id="Tires" name="requestType" value="Tires">
<label for="Tires">Tires</label>
</div>
</div>
<div class='form-group' style="margin-left: 60%;">
<div class="row">
<input type="submit" value="Submit"/>
</div>
</div>
</div>
}
add enum
public enum RequestType
{
Claim = 1,
ScheduledService = 2,
Tires = 3
}
in your action
public ActionResult YourAction(RequestType requestType)
{
//......................................
model.GarageId = //your value
switch (requestType)
{
case RequestType.Claim:
model.requestId = (int)RequestType.Claim;
break;
case RequestType.ScheduledService:
model.requestId = (int)RequestType.ScheduledService;
break;
case RequestType.Tires:
model.requestId = (int)RequestType.Tires;
break;
}
//get insert........................
}
I have a project were you select dates in a list, and than report x-amount of hours on a project on. It looks like this:
But what I want to is, I want to add a check-box after the months name if I want to select all dates under that month. But I am currently not sure how I would do that so I would be glad if I could get some guidance.
This is the view that prints out all the dates:
<form class="form-horizontal">
<div class="portlet-body form">
<div class="form-group">
#if (ViewBag.MissingDays != null)
{
int i = 0;
var months = ((List<DateTime>)ViewBag.MissingDays).GroupBy(x => x.Month);
IEnumerable<IGrouping<int, DateTime>> groups = months as IList<IGrouping<int, DateTime>> ?? months.ToList();
foreach (var group in groups)
{
i++;
var month = CultureInfo.CreateSpecificCulture("sv-SE").DateTimeFormat.GetMonthName(group.Key);
if (groups.Count() > 1)
{
<div class="panel-group accordion" id="accordion1">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1" href="#collapse_#i">
#month
</a>
</h4>
</div>
<div id="collapse_#i" class="panel-collapse collapse">
<div class="panel-body">
<div class="col-md-12">
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" id="isoDate" name="isoDate" value="#isoDate" />#day-#isoDate
</label>
}
</div>
</div>
</div>
</div>
</div>
}
else
{
<div class="col-md-12">
#foreach (var date in group)
{
var isoDate = date.ToString("yyMMdd");
var day = date.ToString("ddd", new CultureInfo("sv-SE")).Substring(0, 2);
<label style="padding-left: 10px">
<input type="checkbox" id="isoDate" name="isoDate" value="#isoDate" />#day-#isoDate
</label>
}
</div>
}
}
}
</div>
</div>
And this is the script on how I select the dates right now.
$(document).ready(function() {
$('input[name="isoDate"]').change(function() {
$("#date").val("");
$('input[name="isoDate"]').each(function() {
if (this.checked) {
$("#date").val($("#date").val() + " " + $(this).val());
}
});
});
});
You can try like this..
First remove the id="isoDate" as Id should be unique. And add a check box inside div near to month field
<input type="checkbox" class="selectAll" name="all" />
Now add a JQuery click handler
$(".selectAll").on("click", function() {
if ($(this).is(':checked')) {
$(this).closest('.panel-default').find("input[name='isoDate']").prop('checked',true);
} else {
$(this).closest('.panel-default').find("input[name='isoDate']").prop('checked',false);
}
});
See working FIDDLE
first time use diferent ids for each input element. Then use js or jquery. Some like this :
var i = 0;
var ids = "juli_150505_" + i;
i++;
then you finde any checkbox element whot you want. By JS or jQuery.
Or you can use class param, then GetElementByClass().
<input type="checkbox" id="isoDate" class="Juli" name="isoDate" value="#isoDate" />
Put a checkbox in front of every month name and give it a class name like 'chkAll'
$('input[name="chkAll"]').click(function(){ //if any chkAll is clicked
if (this.checked) {
$(this).find("input[type='checkbox']").each(function() {
//Loop through
$(this).prop('checked', true);
});
}
else
{
$(this).find("input[type='checkbox']").each(function() {
$(this).prop('checked', false);
});
}
});
I have a search function which works. It searches for registered users, it works when you search only for their partial username, however, the problem with this is that when you load the page, it basically searches, but the search-string is empty, which means it returns every user. I need to make it so it only searches when you actually search. But I can't seem to figure out how to accomplish this. I guess basically I need to stop the form from posting on page load.
#{
Layout = "~/Admin/_SiteLayout.cshtml";
var db = Database.Open("MikZeRCoding2");
var userSearchQuery = "SELECT * FROM [Users] WHERE UserName LIKE '%' + #0 + '%'";
var UsernameSearch = "";
var ErrorMessage = "";
Validation.RequireField("search-username", "lel");
if (IsPost && Validation.IsValid()) {
UsernameSearch = Request.Form["search-username"];
if (UsernameSearch.IsEmpty()) {
ErrorMessage = "You didn't search for anything.";
}
if (!UsernameSearch.IsEmpty() && db.QueryValue(userSearchQuery, UsernameSearch) == null) {
ErrorMessage = "No results for '" + UsernameSearch + "' were found...";
}
else {
}
}
}
<div class="search-users">
<h2>Search users</h2>
<form method="post" action="">
<div class="input-group">
<input type="text" name="search-username" placeholder="Search for a user" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-default glyphicon glyphicon-search" type="button"></button>
</span>
</div>
<input type="submit" value="Search" />
#foreach(var user in db.Query(userSearchQuery, UsernameSearch)) {
<span>[ #user.UserId ]</span> #user.UserName
}
#if(!ErrorMessage.IsEmpty()) {
<div class="alert alert-danger">#ErrorMessage</div>
#Html.ValidationSummary()
}
</form>
</div>
Thank you in advance.
You could wrap your view of the users in a IsPost-statement;
#if(IsPost){
foreach(var user in db.Query(userSearchQuery, UsernameSearch)) {
<span>[ #user.UserId ]</span> #user.UserName
}
}
I'm using bootstrap in my application.
I'm creating dropdown and textbox controls dynamically based on a count and applying validation to those controls.But validation is not working for those textbox controls alone.
Here is my code:
Default.aspx.cs
public partial class DefaultClass
{
public int ddlCount{ get; set; }
public int txtCount{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
}
Default.aspx
<div class="form-horizontal">
<%if (ddlCount > 0)
{
for(int i=0;i<ddlCount ;i++)
{%>
<div class="control-group">
<label class="control-label">DropDown <%=i++%>
</label>
<div class="controls">
<select data-val="true" data-val-required="Field is required" name="">
<option value="">--Select--</option>
<option value=1>Value1</option>
<option value=2>Value2</option>
</select>
</div>
</div>
<%
}
}
if (txtCount> 0)
{
for(int i=0;i<txtCount;i++)
{%>
<div class="control-group">
<label class="control-label">Textbox<%=i++%>
</label>
<div class="controls">
<input type="text" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>
</div>
</div>
<%}
}%>
</div>
<button id="btnSubmit" class="btn btn-success" onclick="Submit();">
Submit</button>
<script type="text/javascript">
$(document).ready(function () {
ConfigureValidator();
});
function ConfigureValidator() {
var basicDetailValidator = $('#Form1').data('validator');
var checkatleastOneCheckboxes = $("input[type='checkbox'][data-val-checkatleastone]");
checkatleastOneCheckboxes.each(function () {
var nameAttr = this.name;
basicDetailValidator.settings.rules[nameAttr].required = true;
basicDetailValidator.settings.messages[nameAttr].required = $(this).attr("data-val-checkatleastone");
});
basicDetailValidator.settings.errorElement = 'span';
basicDetailValidator.settings.errorClass = 'help-inline';
basicDetailValidator.settings.highlight = function (e) {
$(e).closest('.control-group').removeClass('info').addClass('error');
}
basicDetailValidator.settings.success = function (e) {
$(e).closest('.control-group').removeClass('error').addClass('info');
$(e).remove();
}
basicDetailValidator.settings.errorPlacement = function (error, element) {
if (element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('.controls');
if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
} else if (element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
} else {
error.insertAfter(element);
}
};
}
function Submit() {
if (!$('#Form1').valid()) {
return false;
}
}
</script>
I'm using js/jquery.validate.min.js , js/uncompressed/jquery.validate.js and js/uncompressed/jquery.validate.unobtrusive.js .
Validation is not working for textbox controls alone.
Please help me out.
try by including name attribute may it work
<input type="text" name="text_box" id="txtId_<%= i++%>" data-val="true" data-val-required="Field is required"/>