I am trying to create a search filter, each time I insert data type an int, it throws an error to below line and need some help, as to how to resolve it.
When I step into the method Json GetStringData where error is thrown, I saw the 'SearchValue' is undefined.
How does this become possible? How can I change this in order for this code to work? As in where the error is thrown, the data does come back from record, the issue is when search filter is inserted.
ASP.Net
//GET: SearchPeople-ID.
public ActionResult SearchPeopleDetails()
{
RegCoursesViewModel regCoursesView = new RegCoursesViewModel();
return View(cb.RegPeopleLists.ToList());
}
// GET://Passing-Data-Back as Json.
public JsonResult GetSearchingData(string SearchBy, string SearchValue)
{
List<eNtsaRegPeopleLists> regPeopleLists = new List<eNtsaRegPeopleLists>();
if(SearchBy == "ID")
{
try
{
int Id = Convert.ToInt32(SearchValue); // Incorrect string format
regPeopleLists = cb.RegPeopleLists.Where(v => v.LoginID == Id || SearchValue == null).ToList();
}catch(FormatException)
{
Console.WriteLine("{0} Is Not A ID ", SearchValue);
}return Json(regPeopleLists, JsonRequestBehavior.AllowGet);
}
else
{
regPeopleLists = cb.RegPeopleLists.Where(v => v.Name.StartsWith(SearchValue) || SearchValue == null).ToList();
return Json(regPeopleLists, JsonRequestBehavior.AllowGet);
}
}
public class eNtsaRegPeopleLists
{
public string Name { get; set; }
[Key]
public int LoginID { get; set; }
public string SISID { get; set; }
public string Role { get; set; }
public DateTime LastActivity { get; set; }
public decimal TotalActivity { get; set; }
}
Javascript
<!--Javascript functionality for filter search-->
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#SearchLv").keyup(function () {
var SearchBy = $("#SearchBy").val();
var SearchValue = $("#Search").val();
var SetData = $("#DataSearching");
SetData.html("");
debugger;
$.ajax({
type: "post",
url: "/Home/GetSearchingData?SearchBy=" + SearchBy + "&SearchValue=" + SearchValue,
contentType: "html",
success: function (result) {
if (result.length == 0) {
SetData.append('<tr style="color:red"><td colspan="3">No Match Data</td></tr>')
}
else {
$.each(result, function (index, value) {
var Data = "<tr>" +
"<td>" + value.LoginID + "</td>" +
"<td>" + value.Name + "</td>" +
"<td>" + value.Role + "</td>" +
"<td>" + value.SIS_ID + "</td>" +
"<td>" + value.LastActivity + "</td"> +
"<td>" + value.TotalActivity + "</td>"
"</tr>";
SetData.append(Data);
});
}
}
});
});
});
</script>
View
#model IEnumerable<eNtsaRegistrationTraining.Models.eNtsaRegPeopleLists>
<br />
<br />
<div class="form-group row float-right">
<form class="form-group ml-lg-auto">
<div class="input-group input-group-sm">
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="SearchLv">
<div class="input-group-append">
<button class="btn btn-navbar" type="submit">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</form>
</div>
<!--Select-ID-->
<select id="SearchBy">
<option value="ID">LoginID</option>
<option value="Name">Name</option>
<option value="Roles">Roles</option>
</select>
<br />
<br />
<table class="table table-bordered">
<thead>
<tr>
<th>LoginID</th>
<th>Name</th>
<th>Roles</th>
<th>SISID</th>
<th>LastActivity</th>
<th>TotalActivity</th>
</tr>
</thead>
<!--Tbody here-->
<tbody id="DataSearching">
#foreach(var Item in Model)
{
<tr>
<td>#Item.LoginID</td>
<td>#Item.Name</td>
<td>#Item.Role</td>
<td>#Item.SISID</td>
<td>#Item.LastActivity</td>
<td>#Item.TotalActivity</td>
</tr>
}
</tbody>
</table>
search input id is {SearchLv} in your view.
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="SearchLv">
Either change the id in view
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="Search">
Or you can change on javascript
var SearchValue = $("#SearchLv").val();
public string strSubCat = "";
strCategory += #"<li class='dropdown menu-large nav-item'><a href='# class='dropdown-
toggle nav-link' data-toggle='dropdown'>" + dr["Category_name"] +# </a>
<ul class='dropdown-menu megamenu'>
<div class='row'>
"string subcat1 = null;
subcat1 +=strSubCat + #"
</div>
</ul>
</li>";
Miss some double quotes and ";"
Try this : ?
string strSubCat = "";
strCategory += #"<li class='dropdown menu-large nav-item'><a href='# class='dropdown-
toggle nav-link' data-toggle='dropdown'>" + dr["Category_name"] + #" </a>
<ul class='dropdown-menu megamenu'>
<div class='row'>;
";
string subcat1 = null;
subcat1 +=strSubCat + #"
</div>
</ul>
</li>";
I get the following exception in my system.This system worked properly. But suddenly got and exception. I tried doing debugging. But I couldn't find the anything. This is about a profile picture upload. I did some removing of code and I got the error. But then I again add those codes but nothing happen. I tried some solutions in the internet but didn't work. I'm new to this work so please help me if you can. I tried removing some of the codes then I got an error saying invalid operation.
How can I fix this?
I tried to debug and find where the problem occurs, unfortunately I couldn't find where it is.But I guess the problem should be in these codes. These two codes created the exception
Code part 1
#{
var imgUrl = #Url.Content("~/Content/profile/" + Model.SID + ".png") + "?time=" + DateTime.Now.ToString();
}
<img id="user_img" src="#imgUrl" height="50" width="50" style="margin-top:2px" />
</li>
Code part 2
#if (Model.SID != null)
{
var imgUrl = #Url.Content("Content/profile/" + Model.SID + ".png") + "?time=" + DateTime.Now.ToString();
<div class="input-field col s12">
<div class="input-field col s12">
<img id="user_img" src="#imgUrl" height="1" width="1" />
</div>
<div class="mngimg">
#using (Html.BeginForm("UploadPhoto", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="input-field col s12">
<input type="file" name="file" id="files" onchange="this.form.submit()" />
</div>
}
</div>
</div>
}
#section Scripts
{
<script>
$(document).ready(function () {
$.validator.setDefaults({
errorClass: 'invalid',
validClass: "valid",
errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("label[for='" + element.attr("id") + "']")
.attr('data-error', error.text());
},
submitHandler: function () {
event.preventDefault();
var SID = $("[name='SID']").val();
var fName = $("[name='fname']").val();
var lName = $("[name='lname']").val();
var dob = $("[name='dob']").val();
var email = $("[name='email']").val();
var pw = $("[name='password']").val();
var confirmPw = $("[name='confirmPassword']").val();
var phone = $("[name='phone']").val();
var address = $("[name='address']").val();
var user = {
SID: SID,
FirstName: fName,
LastName: lName,
DOB: dob,
email: email,
Password: password,
Phone: phone,
Address: address
}
//console.log(SID + " " + email + " " + password);
$.ajax({
type: 'POST',
url: 'saveChanges',
contentType: 'application/json',
data: JSON.stringify(user),
dataType: 'Json',
async: true,
success: function (data) {
if (data == true) {
Materialize.toast('Details Updated Successfully !!!', 4000, 'blue')
}
}
});
}
});
$.validator.addMethod("regx", function (value, element, regexpr) {
return regexpr.test(value);
}, "must contain more than 8 characters & at least 1 Alphabet and 1 Number");
$("#form").validate({
rules: {
SID: {
required: true,
minlength: 10,
maxlength: 10
},
fName: {
required: true,
minlength: 4,
maxlength: 20
},
lName: {
required: true,
minlength: 4,
maxlength: 20
},
dob: {
required: true,
},
email: {
required: true,
email: true
},
Phone: {
required: true,
regx: /^\d{10}$/,
minlength: 10,
maxlength: 10
},
},
messages: {
fName: {
required: true,
minlength: "Should be minimum 4 characters",
maxlength: "Should be maximum 20 characters",
},
lName: {
required: true,
minlength: "Should be minimum 4 characters",
maxlength: "Should be maximum 20 characters"
},
Phone: {
minlength: "Enter valid phone number",
maxlength: "Enter valid phone number"
}
}
});
});
</script>
}
<form id="form" style="width:100%; height:auto; margin-left:1%; margin-top:1%" method="post">
#*<div class="input-field col s12 ">
<i class="material-icons prefix">account_circle</i>
<input id="img" name="img" type="image" value="" readonly="readonly" style="margin-top:5%; margin-bottom:1%">
<label for="img">Profile Picture</label>
</div>*#
<div class="input-field col s12 ">
<i class="material-icons prefix">subtitles</i>
<input id="SID" name="SID" type="text" value="#Model.SID" readonly="readonly">
<label for="SID">Student ID</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="fname" name="fname" type="text" class="validate" value="#Model.FirstName">
<label for="fname">First Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="lname" name="lname" type="text" class="validate" value="#Model.LastName">
<label for="lname">Last Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">Address</i>
<input id="address" name="address" type="text" class="validate" value="#Model.Address">
<label for="lname">Address</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">phone</i>
<input id="phone" name="phone" type="text" class="validate" value="#Model.Phone">
<label for="lname">Phone</label>
</div>
<label for="dob" style="margin-left:10%">Date of Birth</label>
<div class="input-field col s12">
<i class="material-icons prefix">D</i>
<input id="dob" name="dob" type="date" class="validate" value="#Model.DOB.Value.ToString("dd/ MM/ yyyy")"> #*#Model.DOB.Value.ToString("mm/dd/yyyy")*#
</div>
<div class="input-field col s12">
<i class="material-icons prefix">email</i>
<input id="email" name="email" type="email" class="validate" value="#Model.email">
<label for="email">Email</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">lock_outline</i>
<input id="password" name="password" type="password" class="validate">
<label for="password">Password</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">lock_outline</i>
<input id="confirmPassword" name="confirmPassword" type="password" class="validate" onkeyup="check()">
<label for="confirmPassword">Confirm Password</label>
<lable name="checkpassword"></lable>
</div>
<div class="input-field col s12">
<input class="btn waves-effect waves-light" id="submit" type="submit" name="action" style="width:33%; margin-left:20%; margin-bottom:4%">
</div>
#*</div>*#
</form>
Controller
public ActionResult Index()
{
Session["userID"] = "IT14111884";
string sessionValue = Session["userID"].ToString();
if (Session["userID"].ToString() == null) return View("Login");
person1 = repo.GetPeronById(sessionValue);
var model = person1;
//DateTime da = (DateTime)person1.DOB;
//DateTime date2 = ;
//DateTime.ToString("dd MMM yyyy")
return View(model);
}
[HttpPost]
public JsonResult saveChanges(person person1)
{
person _person = new person();
_person.SID = person1.SID;
_person.FirstName = person1.FirstName;
_person.LastName = person1.LastName;
_person.Address = person1.Address;
_person.Phone = person1.Phone;
_person.DOB = person1.DOB;
_person.password = person1.password;
_person.email = person1.email;
//Session["_person"] = _person;
string sessionValue = Session["userID"].ToString();
bool status;
if (!ModelState.IsValid) return Json(false, JsonRequestBehavior.AllowGet);
status = repo.updatePerson(sessionValue,_person);
return Json(status, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult UploadPhoto(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var user = Session["userID"].ToString();
var fileExt = Path.GetExtension(file.FileName);
if (fileExt.ToLower().EndsWith(".png") || fileExt.ToLower().EndsWith(".jpg"))
{
var fileName = user + ".png";
var filePath = HostingEnvironment.MapPath("~/Content/profile/") + fileName;
var directory = new DirectoryInfo(HostingEnvironment.MapPath("~/Content/profile/"));
if (directory.Exists == false)
{
directory.Create();
}
ViewBag.FilePath = filePath.ToString();
file.SaveAs(filePath);
return RedirectToAction("Index", new { Message = ManageMessageId.PhotoUploadSuccess });
}
else
{
return RedirectToAction("Index", new { Message = ManageMessageId.FileExtensionError });
}
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
public enum ManageMessageId
{
Error,
PhotoUploadSuccess,
FileExtensionError
}
Reporsitory class
public bool updatePerson(string ID,person _objPerson)
{
//_dbContext.people.Add(_objPerson);
person temp = null;
try
{
temp = (from p in _dbContext.people
where p.SID == ID
select p).SingleOrDefault();
temp.FirstName = _objPerson.FirstName;
temp.LastName = _objPerson.LastName;
temp.Address = _objPerson.Address;
temp.Phone = _objPerson.Phone;
temp.DOB = _objPerson.DOB;
temp.password = _objPerson.password;
temp.email = _objPerson.email;
//_dbContext.SaveChanges();
//Guid id = _objPerson.Person_ID;
if (_dbContext.SaveChanges() > 0)
{
return true;
}
}
catch (DbUpdateException e)
{
string msg = (e.InnerException.Message);
//Console.ReadLine();
}
return false;
}
Here's the deal, I making a website that sells some products and according to how much products I have the ammount of buttons changes too.
For example if I have 5 products I will have 5 buttons, something like this:
What I want to do is when a button is clicked I want to take the item name and save it (in a session) so I can use this information on a different page (the code behind is in C#).
How can I do this?
Html:
<div runat="server" id="CatalogProducts" class="container-fluid">
</div>
Code behind:
SqlHey SQLViewProducts = new SqlHey();
DataSet DSViewProducts = new DataSet();
string Sheilta = "SELECT TblShop.ItemName, TblShop.Price, TblShop.ShopType, TblShop.Image, TblShop.Description FROM TblShop;";
DSViewProducts = SQLViewProducts.chkData(Sheilta);
int I;
for (I = 0; I < DSViewProducts.Tables[0].Rows.Count; I++)
{
if (DSViewProducts.Tables[0].Rows.Count % 2 == 0)
{
if (I % 2 == 0)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div>";
else CatalogProducts.InnerHtml += " <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
}
if (DSViewProducts.Tables[0].Rows.Count % 2 != 0)
{
if (I + 1 == DSViewProducts.Tables[0].Rows.Count)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div>";
if (I % 2 == 0)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
else CatalogProducts.InnerHtml += " <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
}
}
The methood chkData:
public DataSet chkData(string sqlstr)
{
string path = HttpContext.Current.Server.MapPath("~/App_Data/");
string fileName = "Hey.mdb";
path += fileName;
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + path;
OleDbConnection conn = new OleDbConnection(connString);
OleDbDataAdapter da = new OleDbDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
In the CatalogProducts.InnerHtml bind the for loop count to button ID,if not possible to bind then try instead of asp button you may use input type="button"
I just added to your code refer this..
<input type="Button" id=\"Button_\"+I />
It's better to use Repeater for this solution. Check out this link. It will tell you what to do step by step.
It is such that I have a Repeater with both label and Literal content, and that is how I got it into Repeater and I would like it being like shown at the side.
It appears with the error that tells me that it can not find my label or Literal
Repeater her:
<asp:Repeater ID="RepeaterOpslag" runat="server">
<ItemTemplate>
<div id="forslagbox" runat="server">
<asp:Label ID="LabelBrugernavn" runat="server"></asp:Label>
<asp:Literal ID="LiteralLikesOpslag" runat="server"></asp:Literal>
<asp:Literal ID="LiteralDelete" runat="server"></asp:Literal>
<div style="margin-bottom: 5px; clear: both;"></div>
<asp:Label ID="LabelText" runat="server"></asp:Label>
<div style="margin-top: 5px; clear: both;"></div>
<div class="col-md-12">
<hr class="tall" style="margin: 7px 0;">
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Default.aspx.cs here, It is in foreach which gives me problems that it will not print any of it at all.
RepeaterOpslag.DataSource = db.ForslagOpslags.ToList();
RepeaterOpslag.DataBind();
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
var likesFjern = db.ForslagOpslagLikes.Where(a => a.fk_brugerid == Helper.ReturnBrugerId()).Count();
LabelBrugernavn.Text = item.brugere.fornavn + " " + item.brugere.efternavn;
LabelText.Text = item.text;
if (likesFjern >= 1)
{
LiteralLikesOpslag.Text = "<a href='fjernsynesgodtom.aspx?id=" + item.Id + "&brugerid=" + Helper.ReturnBrugerId() + "' class='btn btn-danger btn-xs'>Fjern synes godt om</a>";
}
else if (item.brugere.Id != Helper.ReturnBrugerId())
{
LiteralLikesOpslag.Text = "<a href='SynesGodtOm.aspx?id=" + item.Id + "' class='btn btn-success btn-xs'>Like opslag - " + item.ForslagOpslagLikes.Count() + " synes godt om</a>";
}
else
{
LiteralLikesOpslag.Text = "<p class='label label-lg label-success'>" + item.ForslagOpslagLikes.Count() + " synes godt om</p>";
}
if ((item.fk_brugerid == Helper.ReturnBrugerId() || Helper.BrugerRank(Helper.ReturnBrugerId()) == 1))
{
LiteralDelete.Text = "<a href='slet.aspx?id=" + item.Id + "' class='btn btn-danger btn-xs'>Slet</a>";
}
}