How to display a modal without using the onClick function - javascript

I would like to know how I can open a modal without clicking on a button. Basically if a user searches for something and the search does not return an results I would like a modal to popup informing the user that the search did not yield any results. I have pasted my code below but I dont think I am supposed to be calling jquery from within html.
<table id="tableData" class="table">
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
MobileNumber
</th>
<th>
EmailAddress
</th>
<th>
Identification Number
</th>
</tr>
#foreach (var item in Model)
{
if(Model.Count == 0)
{
$('#myConfirmationModal').modal('show');
//alert("no results find");
}
<tr>
<td>
<a class="anchorDetail" href="javascript:;" data-id=#item.ClientId>#item.FirstName</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MobileNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdentificationNumber)
</td>
</tr>
}
</table>

You basically need to execute $(#....).modal('show') after the page is loaded if the count is 0. Execute the code inside $(function(){...}). JQuery will make sure to execute the function inside $(...) after document is loaded i.e. same as $(document).ready(function(){...})
Try below.
if(Model.Count == 0) {
<script>
$(function() {
{
$('#myConfirmationModal').modal('show');
//alert("no results find");
}
});
</script>
} else {
#foreach (var item in Model) {
...
...
}

Related

How to save items to cart using localStorage

So I have a table like this:
<table border="1">
<tbody>
<tr>
<th> Book Title </th>
<th> Author </th>
<th> Book </th>
</tr>
<tr>
<td id= Book_Title>Gone </td>
<td id= Author>Micheal Grant</td>
<td><button id="AddToCart" onclick="addToLocalStorage()">Add To Cart</button> </td>
</tr>
<tr>
<td id= Book_Title>The Knife of never letting go</td>
<td id= Author>Ryan Howard</td>
<td><button id="AddToCart" onclick="addToLocalStorage()">Add To Cart</button> </td>
</tr>
</tbody>
My goal is to have, on button click for the data of a specific row to be saved to local storage. However, because the id's are the same for each row only the first instance of the id will save. I was wondering how I could use jquery closest() to fix my problem. Or even if there is any other solution to my problem.
In order to save the data contained in your table's row... Like the book title and author, I suggest you to use some objects contained in an array.
Then you'll have to stringify that prior to use localStorage.
When you'll want to retreive the stored data, you'll have to parse it back to an array of objects.
Sadly, SO snippets do not like the use of localStorage... So my working demo is on CodePen.
Here's the relevant code:
// The "add to cart" handler.
$("table").on("click", ".AddToCart", function(e){
// Get previous storage, if any.
var storage = JSON.parse(localStorage.getItem("cart"));
if(storage==null){
storage = [];
}
var row = $(this).closest("tr");
var title = row.find("td").eq(0).text().trim();
var author = row.find("td").eq(1).text().trim();
// Create an object to store.
var data = {author:author,title:title};
storage.push(data);
// Store it.
localStorage.setItem("cart",JSON.stringify(storage));
});
Use classes instead of IDs, and attach the listener using Javascript instead of inline attributes (which is as bad as eval). No need for jQuery. For example:
document.querySelector('table').addEventListener('click', (e) => {
if (e.target.className !== 'AddToCart') return;
// e.target refers to the clicked button:
const [bookTd, authorTd] = [...e.target.closest('tr').children];
addToLocalStorage({ title: bookTd.textContent, author: authorTd.textContent });
});
function addToLocalStorage(obj) {
console.log('adding ' + obj);
}
<table border="1">
<tbody>
<tr>
<th> Book Title </th>
<th> Author </th>
<th> Book </th>
</tr>
<tr>
<td class="Book_Title">Gone </td>
<td class="Author">Micheal Grant</td>
<td><button class="AddToCart">Add To Cart</button> </td>
</tr>
<tr>
<td class="Book_Title">The Knife of never letting go</td>
<td class="Author">Ryan Howard</td>
<td><button class="AddToCart">Add To Cart</button> </td>
</tr>
</tbody>
</table>

I want to check the property value whether its empty or not in MVC. Please suggest

Here is my CShtml code
I would like to check the Employee name for some condition.
Would be great if you can suggest.
#model IEnumerable<ATS.Models.clsManagerApproval>
#{
ViewBag.Title = "ManagerApproval";
Layout = "~/Views/Shared/_Layoutuser.cshtml";
}
<h2>Manager Approval</h2>
<script type="text/javascript">
$(document).ready(function () {
if ($("#EmployeeName").val() == "") {
alert("some sample text abc213");
}
})
</script>
<table style="border: 1px solid white">
<tr>
<th style="width:1px; visibility:collapse;">
#Html.DisplayNameFor(model => model.UAmasterID)
</th>
<th style="width:130px">
#Html.DisplayNameFor(model => model.EmployeeName)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td style="visibility:collapse;">
#Html.DisplayFor(modelItem => item.UAmasterID)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmployeeName)
</td>
</tr>
}
</table>
I would like to check the Employee name for some condition.
Would be great if you can suggest.
Thanks
#{
if(string.IsNullOrEmpty(Model.EmployeeName))
{}
}
#foreach (var item in Model) {
if(string.IsNullOrEmpty(Model.EmployeeName))//here your condition
{
//whatever u want to do...
}
else{
<tr>
<td style="visibility:collapse;">
#Html.DisplayFor(modelItem => item.UAmasterID)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmployeeName)
</td>
</tr>
}
}
You need to understand how MVC / razor works.
Everything after an # symbol is razor and will be executed on the server before it is sent to the client. This allows you to manipulate the Model object using C# functions.
Javascript code is entirely separate from razor because javascript is executed on the client.
Razor will automatically detect when you want html so you can write code like this:
#foreach(var item in Model)
{
#if (string.IsNullOrEmpty (Model.EmpleeName) )
{
Warning: Name is blank
} else {
...
...
...
}
}
It sounds like you may need to do some background reading about MVC.

Live search partialview loads as full view with Ajax.BeginForm

I´m trying to create a live search mechanism using Ajax and partialviews. The idea is that the main view is simply a text box without submit button (this is a main requirement for the program). The user types in the box and an onchange command activates a javascript function which submits the form into a controller. The controller will then make a database search and return a partialview filled with a table of results to substitute a div in the original view.
My problem is that the partialview with the results loads as a full view, over the index and search views.
These are my code snippets starting with the index view.
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="buscar">
#Html.Action("Buscar", "Reportes")
</div>
<div id="encontrar-form">
</div>
Now the partialview with the search button
#model IEnumerable<ProyectoTamaulipas.Reporte>
<script>
function showRes () {
document.getElementById("forma").submit();
}
</script>
<div>
<br />
<br />
<h2>Haga una búsqueda por número de folio</h2>
<p>
#using (Ajax.BeginForm("Buscar", "Reportes", FormMethod.Post, new AjaxOptions(){
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "encontrar-form"
}, new { id = "forma" }))
{
<input type="text" name="numero" onchange="showRes()" />
}
</p>
</div>
Now the relevant controllers
[HttpGet]
public ActionResult Buscar()
{
return PartialView("First");
}
[HttpPost]
public PartialViewResult Buscar(string numero)
{
if (numero != null)
{
int numeroF = 0;
//var query = (from a in db.Reporte
// where SqlMethods.Like(a.Calle1, "%" + parm + "%")
// select a).ToList();
List<Reporte> query = null;
if (Int32.TryParse(numero, out numeroF))
{
query = (from a in db.Reporte
where a.Folio == numeroF
select a).ToList();
}
return PartialView("reporte", query);
}
ViewBag.Message = "no se encontraron resultados";
return PartialView("reporte");
}
Finally the results view.
#model IEnumerable<ProyectoTamaulipas.Reporte>
#ViewBag.Message
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UCivil_ID)
</th>
<th>
#Html.DisplayNameFor(model => model.ServicioID)
</th>
<th>
#Html.DisplayNameFor(model => model.Ubicacion)
</th>
<th>
#Html.DisplayNameFor(model => model.Calle1)
</th>
<th>
#Html.DisplayNameFor(model => model.Calle2)
</th>
<th>
#Html.DisplayNameFor(model => model.ColoniaID)
</th>
<th>
#Html.DisplayNameFor(model => model.Comentarios)
</th>
<th>
#Html.DisplayNameFor(model => model.EstatusID)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UCivil_ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ServicioID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Ubicacion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Calle1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Calle2)
</td>
<td>
#Html.DisplayFor(modelItem => item.ColoniaID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comentarios)
</td>
#*<td>
#Html.DisplayFor(modelItem => item.Fotografia)
</td>*#
<td>
#Html.DisplayFor(modelItem => item.EstatusID)
</td>
</tr>
}
</table>
I already tried changing several commands and verifying the instalation of my unobtrusive ajax as well as several other things. Sorry for the long question but I've been going at this for two workdays with no luck. Thanks for the help!
I solved it by calling the jquery.unobtrusive-ajax.js on layout intead of on individual views and changing the
document.getElementById("forma").submit();
for a
$("#forma").trigger("submit");
on the search function inside the search partialview called First.

Query Database Using JavaScript

I am fairly new to JavaScript and never used Ajax before. I want to add an OnClick to the Index.cshtml, so when a row is clicked, my code will query database (MSSQL)and return results.
I have two tables in database, User and Contact. The primary key in User, UID, is the foreign key in Contact. Here's my code:
Controller
private UserInfoEntities db = new UserInfoEntities();
public ActionResult Index(){
var users = from u in db.User orderby u.UID select u;
return View(users.ToList());
}
View
#<Info.Model.User>
<script type="text/javascript">
function showEmail() {
var tb = document.getElementById("users");
var rows = tb.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = (function() {
//some code that query Contact table using UID
// and return Contact.Email in a popup windows or something
});
}
}
</script>
<table class="table" id="users" onclick="showEmail()">
<tr>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.UID)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.UID)
</td>
</tr>
Any help is appreciated!
try this;
<script type="text/javascript">
function showEmail() {
//some code that query Contact table using UID
// and return Contact.Email in a popup windows or something
}
</script>
<table class="table" id="users" >
<tr>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstOrDefault().UID)
</th>
</tr>
#foreach (var item in Model) {
<tr onclick="showEmail()">
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.UID)
</td>
</tr>
}

Restrict on-click event for particular column

Can anyone let me know how to disable on click event for particular column.
Scenario : We displayed user details in a table , once click has been made on the table row, popup dialog window will appears with more details(Calling ajax request to retrieve details from database) . But our constraint is to disable on click event for single column associated with the table.
Eg :
<table border = '1'>
<tr>
<th> Name </th>
<th> Id </th>
<th> Phone Number</th>
</tr>
<tr onclick = "testing()">
<td> Krupa </td>
<td> 123 </td>
<td> <a href = "http://www.google.com" target= '_blank'>Click me </a> </td>
</tr>
</table>
If click has been made on text(1st and 2nd column) , it will invoke on click event . But if user clicks on hyper link (3rd column) , i want to redirecting it to Google but not on-click event(testing()).
Can anyone help me to achieve this
Try this:
//snip
<tr>
<td onclick = "testing()"> Krupa </td>
<td onclick = "testing()"> 123 </td>
<td> <a href = "http://www.google.com" target= '_blank'>Click me </a> </td>
</tr>
//snip
Try this
Add a class named templatecell to the corresponding td to prevent click.
<table border = '1'>
<tr>
<th> Name </th>
<th> Id </th>
<th> Phone Number</th>
</tr>
<tr onclick = "testing()">
<td> Krupa </td>
<td> 123 </td>
<td class="templatecell"> <a href = "http://www.google.com" target= '_blank'>Click me </a> </td>
</tr>
</table>
script goes like this
$("table").on("click","td", function(e){
if($(e.target).closest(".templatecell").length){
//Clicked hyper link
//do action and return from here
return;
}
//Else clicked on td cell show popup
})
function testing() {
alert('testing')
}
$(document).ready(function () {
$('table tr td').click(function () {
if ($(this).index() < 2) {
testing();
}
else {
// window.open($(this).find('a').attr('href')); //working
$(this).find('a')[0].click();
}
});
});

Categories

Resources