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
}
}
Related
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 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>
right now I am working on a web-site and I need to insert some users into my database using C# for backend and AngularJS for frontend. If I use postman, everything works fine, the routes are good, but I have a problem when I try to insert them via angularJS. Here is my db structure
my HTML code
<div class="main" ng-controller="newcandidateController as vm">
<form>
<div class="myInputs">
<div class="form-group">
<input type="text" placeholder=" Full name" id="i1" ng-model="vm.name">
</div>
<div class="form-group">
<input type="text" placeholder=" Email" ng-model="vm.email">
</div>
<div class="form-group">
<input type="text" placeholder=" Phone" ng-model="vm.phone">
</div>
<p id="username">Username: </p>
<p id="password">Password: </p>
<div>
<p>Position</p>
<select class="form-control" ng-model="vm.position">
<option ng-repeat="obj in vm.Tests">{{obj.testType}}</option>
</select>
</div>
<div class="form-check">
<br />
<label>Admin: </label>
<input type="checkbox" name="admin" id="checkbox" ng-model="vm.isadmin">
</div>
<input class="btn btn-info" type="button" value="Generate credentials" id="g" ng-click="vm.generate()">
<input class="btn btn-info" type="button" value="Submit" ng-click="vm.postUser()">
</div>
</form>
and my JavaScript file
vm.postUser = function () {
if (vm.position == "SysAdmin") {
vm.test = 2;
} else if (vm.position == "Java soft engineer") {
vm.test = 3;
} else if (vm.position == "SQL Solutions Architect") {
vm.test = 4;
} else {
vm.test = 5;
}
vm.date = "";
vm.time = "";
dataContext.addUser(vm.name, vm.email, vm.phone, vm.position, vm.username, vm.password, vm.isadmin, vm.test, vm.date, vm.time).then(
function (response) {
console.log(vm.name + " " + vm.email + " " + vm.phone + " " + vm.position + " " + vm.username + " " + vm.password + " " + vm.isadmin + " " + vm.test + " " + vm.date + " " + vm.time);
alert("It worked!");
},
function (error) {
console.log(error);
}
);
};
I don't know how to define a default value for date and time cuz at first I want them to be 0 and update it later.
Any help would be awesome, thank you!
edit:
Here is method where I post a user
public User CreateUser(User user)
{
db.User.Add(user);
db.SaveChanges();
return user;
}
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);
});
}
});
Im making PostHelper.cshtml in App_Code folder inside my Blog project. And I got this error on line:
<div class="commentsTab">
#Post.comments.Count**
</div>
and:
#foreach (tag Tag in **Post.tags**)
when Im deleting "#Post.comments.Count" its fine but Ive got similar line and there's no errors:
<div class="postTitle">#Post.Title</div>
whats wrong with this? There's whole code:
#using Blog.Models;
#helper Render(post Post, System.Web.Mvc.HtmlHelper html, bool isAdmin, bool showComments)
{
<div class="postTitle">#Post.Title</div>
<div class="postContainer">
<div class="postTabs">
<div class="dateTab">
<div class="month">#Post.DateTime.ToString("MMM").ToUpper()</div>
<div class="day">#Post.DateTime.ToString("dd")</div>
</div>
<div class="commentsTab">
#Post.comments.Count
</div>
</div>
<div class="postContent">
<div class="postBody">#html.Raw(Post.Body)</div>
<div class="tagList">
#foreach (tag Tag in Post.tags)
{
<span class="tag">#Tag.Name</span>
}
</div>
<div class="linkList">
<div id="fb-root"></div>
<script>
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pl_PL/sdk.js#xfbml=1&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</div>
</div>
</div>
if (showComments)
{
<div id="commentContainer">
<a id="comments"></a>
#foreach (comment Comment in Post.comments.OrderBy(x => x.DateTime))
{
<div class="comment">
<div class="commentName">
#if (!string.IsNullOrWhiteSpace(Comment.Email))
{
#Comment.Name
}
else
{
#Comment.Name;
}
</div>
said:
<div class="commentBody">#html.Raw(html.Encode(Comment.Body).Replace("\n", "<br/>"))</div>
<div class="commentTime">at #Comment.DateTime.ToString("HH:mm") on #Comment.DateTime.ToString("yyyy/MM/dd")</div>
</div>
}
<div id="commentEditor">
<div id="commentPrompt">Leave a comment!</div>
<form action="#Href("~/Posts/Comment/" + Post.ID)" method="post">
<input type="text" id="commentNamePrompt" name="name" /> Name (required)<br />
<input type="text" id="commentEmailPrompt" name="email" /> Email (optional)<br />
<textarea id="commentBodyInput" name="body" rows="10" cols="60"></textarea><br />
<input type="submit" id="commentSubmitInput" name="submit" value="Submit!" />
</form>
</div>
</div>
}
}
My action:
public ActionResult Index(int? id)
{
int pageNumber = id ?? 0;
IEnumerable<post> posts =
(from Post in model.posts
where Post.DateTime < DateTime.Now
orderby Post.DateTime descending
select Post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1);
ViewBag.IsPreviousLinkVisible = pageNumber > 0;
ViewBag.IsNextLinkVisible = posts.Count() > PostsPerPage;
ViewBag.PageNumber = pageNumber;
ViewBag.IsAdmin = IsAdmin;
return View(posts.Take(PostsPerPage));
}
I presume your exception is caused by an already open connection to the DB that you are not closing. In your case try to add a .ToList at the end of your initial select:
select Post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1).ToList();
This will close the reader and copy all results in your memory. See if that makes any difference.
You need MARS. Add: MultipleActiveResultSets=True; to your connection string. See: http://msdn.microsoft.com/en-us/library/ms131686.aspx