I am currently in the process of setting up an MVC entities page with the ability to list all entities of a certain type, using jQuery popups to create new entities, edit or delete existing entities.
As not all entities' details are shown in the list, I would like to provide a details view (read only) which has an edit button in case changes need to be made.
However, at the moment I have not been able to implement this and would welcome any suggestions on how to proceed. Please find the view definitions included below:
Entity Country:
/Views/Country/Index:
#model IEnumerable<MVCjQuerySample2.Entities.Country>
#{
ViewBag.Title = "Countries";
}
<h2>Countries</h2>
<span class="AddLink IconLink"><img src="/Content/Images/Create.png" alt="Add new country" /></span>
<div id="ListBlock"></div>
<div id="EditDialog" title="" class="Hidden"></div>
<div id="DeleteDialog" title="" class="Hidden"></div>
<script type="text/javascript">
$(function () {
$("#EditDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Save": function () {
if ($("#EditForm").validate().form()) {
$.post("/Country/Save", $("#EditForm").serialize(), function (data) {
$("#EditDialog").dialog("close");
$("#ListBlock").html(data);
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$("#DeleteDialog").dialog({
autoOpen: false, width: 400, height: 330, modal: true,
buttons: {
"Delete": function () {
$.post("/Country/Delete", $("#DeleteForm").serialize(), function (data) {
$("#DeleteDialog").dialog("close");
$("#ListBlock").html(data);
});
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".AddLink").click(function () {
$("#EditDialog").html("")
.dialog("option", "title", "Add new Country")
.load("/Country/Create", function () { $("#EditDialog").dialog("open"); });
});
$(".EditLink").live("click", function () {
var id = $(this).attr("itemid");
$("#EditDialog").html("")
.dialog("option", "title", "Edit Country")
.load("/Country/Edit/" + id, function () { $("#EditDialog").dialog("open"); });
});
$(".DeleteLink").live("click", function () {
var id = $(this).attr("itemid");
$("#DeleteDialog").html("")
.dialog("option", "title", "Delete Country")
.load("/Country/DeleteConfirm/" + id, function () { $("#DeleteDialog").dialog("open"); });
});
LoadList();
});
function LoadList() {
$("#ListBlock").load("/Country/List");
}
/Views/Country/List:#using MVCjQuerySample2.Helpers
#model IEnumerable<MVCjQuerySample2.Entities.Country>
<table class="CountryList">
<tr>
<th>Iso</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Iso)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<span class="EditLink IconLink" itemid="#item.Id"><img src="/Content/Images/Pencil.png" alt="Edit" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Pencil.png", "Edit", "Edit", new { id = item.Id })-->
</td>
<td>
<span class="DeleteLink IconLink" itemid="#item.Id"><img src="/Content/Images/Delete.png" alt="Delete" /></span>
<!--#Html.ImageActionLink(#"\Content\Images\Delete.png", "Delete", "Delete", new { id = item.Id })-->
</td>
</tr>
}
</table>
/Views/Country/EditForm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Save", "Country", FormMethod.Post, new { id = "EditForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("CreatedBy")
#Html.Hidden("CreatedOn")
#Html.Hidden("UpdatedBy")
#Html.Hidden("UpdatedOn")
<table>
<tr>
<td>Iso</td>
<td>#Html.TextBox("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.TextBox("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}
<script type="text/javascript">
$(function () {
$("#EditForm").validate({
rules: {
Iso: { required: true },
Name: { required: true }
}
});
});
/Views/Country/DeleteConfirm:
#model MVCjQuerySample2.Entities.Country
#using (Html.BeginForm("Delete", "Country", FormMethod.Post, new { id = "DeleteForm" }))
{
#Html.Hidden("Id")
#Html.Hidden("Iso")
#Html.Hidden("Name")
#Html.Hidden("CreatedOn")
#Html.Hidden("CreatedBy")
#Html.Hidden("UpdatedOn")
#Html.Hidden("UpdatedBy")
<table>
<tr>
<td>Iso</td>
<td>#Html.DisplayText("Iso")</td>
</tr>
<tr>
<td>Name</td>
<td>#Html.DisplayText("Name")</td>
</tr>
<tr>
<td>Created by</td>
<td>#Html.DisplayText("CreatedBy")</td>
</tr>
<tr>
<td>Created on</td>
<td>#Html.DisplayText("CreatedOn")</td>
</tr>
<tr>
<td>Updated by</td>
<td>#Html.DisplayText("UpdatedBy")</td>
</tr>
<tr>
<td>Updated on</td>
<td>#Html.DisplayText("UpdatedOn")</td>
</tr>
</table>
}
Related
I have a table named categories where I store the categories for an E-Commerce. This table has the following aspect:
And this is the user interface to admin the categories.
I want to make a system to sort this table using JQuery.UI.
This is what I tried, but it returns me 500 (Internal Server Error)
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
foreach($categories as $category)
<tr data-index="{{$category->id}}" data-position="{{$category->position}}">
<td class="table-text">{{$category->name}}</td>
<td class="table-text table-justified hide-mobile">
if ($category->visibility)
<i class="far fa-eye"></i>
else
<i class="far fa-eye-slash"></i>
endif
</td>
<td class="table-text table-opts">{{$category->position}}</td>
<td class="table-opts">
<div class="operations">
<a href="{{url('/admin/categories/'.$category->id.'/edit')}}" class="btn-edit pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Editar">
<i class="fas fa-edit"></i>
</a>
<a href="{{url('/admin/categories/'.$category->id.'/delete')}}" class="btn-delete btn-confirm pV-8 pH-12" data-bs-toggle="tooltip" data-bs-placement="top" title="Eliminar">
<i class="fas fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
endforeach
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$('#table_content').sortable({
cancel: 'thead',
stop: () => {
var items = $('#table_content').sortable('toArray', {attribute: 'data-index'});
var ids = $.grep(items, (item) => item !== "");
$.post('{{ url('/admin/categories_list/reorder') }}', {
": $("meta[name='csrf-token']").attr("content"),
ids
})
.fail(function (response) {
alert('Error occured while sending reorder request');
location.reload();
});
}
});
});
</script>
And this is the controller function:
public function postCategoriesReorder(Request $request){
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
foreach ($request->ids as $index => $id){
DB::table('categories')->where('id', $id)->update(['position' => $index+1]);
}
return response(null, Response::HTTP_NO_CONTENT);
}
Consider the following example.
var tableData = [{
id: 1,
name: "Cat 1",
visibility: true,
position: 1
}, {
id: 2,
name: "Cat 2",
visibility: false,
position: 2
}, {
id: 3,
name: "Cat 3",
visibility: true,
position: 3
}, {
id: 4,
name: "Cat 4",
visibility: true,
position: 4
}, {
id: 5,
name: "Cat 5",
visibility: true,
position: 5
}];
$(function() {
function updateTable(data) {
$.each(data, function(i, r) {
var row = $("<tr>", {
"data-index": r.id
}).data("row", r).appendTo("#table_content");
$("<td>", {
class: "table-text"
}).html(r.name).appendTo(row);
$("<td>", {
class: "table-text table-justified hide-mobile"
}).html("<i class='fas fa-eye'></i>").appendTo(row);
if (!r.visibility) {
$(".fa-eye", row).toggleClass("fa-eye fa-eye-slash");
}
$("<td>", {
class: "table-text table-opts"
}).html(r.position).appendTo(row);
$("<td>", {
class: "table-opts"
}).appendTo(row);
$("<div>", {
class: "operations"
}).appendTo($("td:last", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/edit",
class: "btn-edit pV-8 pH-12",
title: "Editor",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-edit'></i>").appendTo($("td:last > div", row));
$("<a>", {
href: "/admin/categories/" + r.id + "/delete",
class: "btn-delete btn-confirm pV-8 pH-12",
title: "Eliminar",
"bs-toggle": "tooltip",
"bs-placement": "top"
}).html("<i class='fas fa-trash-alt'></i>").appendTo($("td:last > div", row));
});
}
function gatherData(table) {
var rows = $("tbody > tr", table);
var item;
var results = [];
rows.each(function(i, el) {
item = $(el).data("row");
item.position = i + 1;
results.push(item);
});
return results;
}
updateTable(tableData);
$('#table_content').sortable({
cancel: 'thead',
start: (e, ui) => {
start = $('#table_content').sortable('toArray', {
attribute: 'data-index'
});
},
stop: () => {
ids = gatherData("table");
console.log(start, ids);
/*
$.post('/admin/categories_list/reorder', {
"csrf-token": $("meta[name = 'csrf-token']").attr("content"),
ids
})
.fail(function(response) {
alert('Error occured while sending reorder request');
location.reload();
});
*/
}
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#fortawesome/fontawesome-free#5.15.4/css/fontawesome.min.css" integrity="sha384-jLKHWM3JRmfMU0A5x5AkjWkw/EYfGUAGagvnfryNV3F9VqM98XiIH7VBGVoxVSc7" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.0/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col" span="1">Nombre</th>
<th scope="col" span="1" class="table-justified hide-mobile">Estado</th>
<th scope="col" span="1" class="table-opts">Orden</th>
<th scope="col" span="1"></th>
</tr>
</thead>
<tbody id="table_content">
</tbody>
</table>
This should allow you to pass the new position for each ID to the script so the Database is updated.
<h2>GetAllProducts</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.AgeId)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.AgeId)
</td>
<td> <button type="button" data-id="#item.Id"
class="productIdButton">AddProductToBasket</button></td>
</tr>
}
#section scripts {
<script type="text/javascript">
$("button").click(function () {
//returns all the product ids
//want to return the selected id of the button clicked
// var h = ($(this).data("id"));
var h= ($(this).attr("data-id"));
var productId = (h.Id);
var s = productId;
//alert(productId);
$.ajax({
url: "/api/BasketAPI/AddProductToBasket/",
type: "POST",
data: { id: productId },
contentType: false,
cache: false,
processData: false,
});
});
</script>
}
I am trying to pass the data-id="#item.Id" value found in the view (JQuery) to the controller and use this value to compare to the Id of a class. I am not sure to get the id value from the ajax request.
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public void AddProductToBasket(int id)
{
var returnAllProductIds = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
At the moment the id from the ajax request (the id is the product id assigned to a button. Each button has a product id assigned to it) is not being passed to the controller. I want the id in the parameter of the method in the controller to be set to the id from the ajax request. At the moment this is not being set.
Please try this.
CSHTML Pages
<h2>GetAllProducts</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.AgeId)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.AgeId)
</td>
<td> <button type="button" onclick="AddProductToBasket(#item.Id)" data-id="#item.Id"
class="productIdButton">AddProductToBasket</button></td>
</tr>
}
JavaScript Code
#section scripts {
<script type="text/javascript">
function AddProductToBasket(productid)
{
try
{
$.ajax({
url: "/api/BasketAPI/AddProductToBasket",
type: "POST",
data: { id: productid },
success: function(oData){
alert(oData);
},
error:function(error)
{
alert(error);
}
});
}
catch(e)
{
alert(e.message);
}
}
</script>
}
Controller Action
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public int AddProductToBasket(int id)
{
var returnProductId = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
return returnProductId;
}
I'm using Laravel 5.6 and Vuejs 2.
If I click on my checkbox and make the value true it's supposed to save a 1 in the database and if I click my checkbox and make the value false it saves a 0.
The problem I'm having is that if I click my checkbox and make it true, it doesn't save the correct value, no changes is made to the database and I don't get any errors. If I click on my checkbox and make it false, it saves the 0 correctly.
I did notice that even when my value is supposed to be true, I do get a false when I dd($category->has('active')
I'm not sure where I'm going wrong or how to fix it.
My vue file
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categoriesNew" >
<td>
<label>checkbox 1</label>
<input name="active" type="checkbox" v-model="category.active" #click="checkboxToggle(category.id)">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: ['categories'],
data(){
return {
categoriesNew: this.categories
}
},
methods: {
checkboxToggle(id){
console.log(id);
axios.put('/admin/category/active/'+id, {
categories: this.categoriesNew
}).then((response) => {
//Create success flash message
})
},
},
mounted() {
console.log('Component mounted.')
}
}
</script>
my routes
Route::put('admin/products/updateAll', 'Admin\ProductsController#updateAll')->name('admin.products.updateAll');
Route::put('admin/category/active/{id}', 'Admin\CategoryController#makeActive')->name('admin.category.active');
Route::resource('admin/category', 'Admin\CategoryController');
Route::resource('admin/products', 'Admin\ProductsController');
my CategoryController#makeActive
public function makeActive(Request $request, $id)
{
$category = Category::findOrFail($id);
if($request->has('active'))
{
$category->active = 1;
}else{
$category->active = 0;
}
$category->save();
}
I hope I made sense. If there is anything that isn't clear or if you need me to provide more info, please let me know
Try changing this line
categories: this.categoriesNew
to
categories: category.active
and add a data prop at the top called category.active: ''
I've managed to get it to work. This is what I did.
vue file
<template>
<div class="card-body">
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Active</th>
<th scope="col">Title</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<tr v-for="(category, index) in categories" >
<td>
<label>checkbox 1</label>
<input type="checkbox" v-model="category.active" #click="checkboxToggle(category)">
</td>
<td>
{{ category.title }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: ['attributes'],
data(){
return {
categories: this.attributes,
}
},
methods: {
checkboxToggle (category) {
axios.put(`/admin/category/${category.id}/active`, {
active: !category.active
}).then((response) => {
console.log(response)
})
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
my routes
Route::put('admin/category/{category}/active', 'Admin\CategoryController#makeActive')->name('admin.category.active');
and my CategoryController#makeActive
public function makeActive(Request $request, $id)
{
$category = Category::findOrFail($id);
if(request('active') === true)
{
$category->active = 1;
}else{
$category->active = 0;
}
$category->save();
}
I have used .NET API to consume it. But the code is not working. Can you please give me solution for the below code?
// State object
List<SelectListItem> state = new List<SelectListItem>();
// Client
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
// JSON type
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
);
// Web API controller
var response1 = client1.GetAsync("api/State");
if (response1.IsSuccessStatusCode) // Response type
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
return Json(state, JsonRequestBehavior.AllowGet);
[HttpGet]
public ActionResult Index()
{
List<Student> EmpInfo = new List<Student>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/StudentApi").Result;
if (response.IsSuccessStatusCode)
{
EmpInfo = JsonConvert.DeserializeObject<List<Student>>(response.Content.ReadAsStringAsync().Result);
return View(EmpInfo);
}
return View();
}
[HttpGet]
public PartialViewResult Edit(int id)
{
StudentViewModel EmpInfo = new StudentViewModel();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var responsecountry = client1.GetAsync("api/Country/").Result;
List<SelectListItem> country = new List<SelectListItem>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/StudentApi/" + id).Result;
if (response.IsSuccessStatusCode)
{
EmpInfo = JsonConvert.DeserializeObject<StudentViewModel>(response.Content.ReadAsStringAsync().Result);
if (responsecountry.IsSuccessStatusCode)
{
country = JsonConvert.DeserializeObject<List<SelectListItem>>(responsecountry.Content.ReadAsStringAsync().Result);
EmpInfo.Country = country;
}
return PartialView(EmpInfo);
}
return PartialView();
}
public ActionResult Create()
{
StudentViewModel student = new StudentViewModel();
List<SelectListItem> country = new List<SelectListItem>();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/Country/").Result;
List<SelectListItem> state = new List<SelectListItem>();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
if (response.IsSuccessStatusCode)
{
country = JsonConvert.DeserializeObject<List<SelectListItem>>(response.Content.ReadAsStringAsync().Result);
student.Country = country;
var response1 = client1.GetAsync("api/State/" + Convert.ToInt32(country.FirstOrDefault().Value)).Result;
if (response1.IsSuccessStatusCode)
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
student.State = state;
}
}
return View(student);
}
public JsonResult GetStates(int countryId)
{
List<SelectListItem> state = new List<SelectListItem>();
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");
client1.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response1 = client1.GetAsync("api/State/" + countryId).Result;
if (response1.IsSuccessStatusCode)
{
state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
return Json(state, JsonRequestBehavior.AllowGet);
}
return Json(state);
}
[HttpPost]
public ActionResult Create(Student student)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("api/StudentApi", student).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return null;
}
[HttpPost]
public ActionResult Update(StudentViewModel student)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2585/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var stu = new Student()
{
Id = student.Id,
FirstName = student.FirstName,
LastName = student.LastName,
DateOfBirth = student.DateOfBirth,
Email = student.Email,
Phone = student.Phone,
CountryId = student.CountryId
};
HttpResponseMessage response = client.PutAsJsonAsync("api/StudentApi/", stu).Result;
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return null;
}
[HttpPost]
public JsonResult EmailExists(string email)
{
return Json(!String.Equals(email, "h#h.com", StringComparison.OrdinalIgnoreCase));
//var user = Membership.GetUser(UserName);
//return Json(user == null);
}
}
-----------
Create
-----------
#model Practice.Web.Models.StudentViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SignUp</title>
<script src="#Url.Content("~/Scripts/jquery-1.12.4.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#CountryId").change(function () {
$("#StateId").empty();
$.ajax({
type: 'GET',
url: '#Url.Action("GetStates")', // we are calling json method
dataType: 'json',
data: { countryId: $("#CountryId").val() },
success: function (state) {
//debugger;
$.each(state, function (i, s) {
$("#StateId").append('<option value="' + s.Value + '">' +
s.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
</head>
<body>
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
</tr>
<tr>
<td>First Name: </td>
<td>
#Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
#Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Date Of Birth: </td>
<td>
#Html.TextBoxFor(m => m.DateOfBirth)
</td>
</tr>
<tr>
<td>Email: </td>
<td>
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(model => model.Email)
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
#Html.TextBoxFor(m => m.Phone)
</td>
</tr>
<tr>
<td>Country: </td>
<td>
#Html.DropDownListFor(m => m.CountryId, Model.Country)
</td>
</tr>
<tr>
<td>State: </td>
<td>
#Html.DropDownListFor(m => m.StateId, Model.State)
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
}
</body>
</html>
-----------------
Edit
---------------------
#model Practice.Web.Models.StudentViewModel
#{
ViewBag.Title = "Edit";
}
<style>
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {
border-radius: 2px;
}
.button2 {
border-radius: 4px;
}
.button3 {
border-radius: 8px;
}
.button4 {
border-radius: 12px;
}
.button5 {
border-radius: 50%;
}
</style>
<div class="modal-body">
#using (Ajax.BeginForm("Update", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divEmp" }))
{
<table cellpadding="0" cellspacing="0">
<tr>
<th colspan="2" align="center">Person Details</th>
#Html.HiddenFor(m => m.Id)
</tr>
<tr>
<td>First Name: </td>
<td>
#Html.TextBoxFor(m => m.FirstName)
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
#Html.TextBoxFor(m => m.LastName)
</td>
</tr>
<tr>
<td>Date Of Birth: </td>
<td>
#Html.TextBoxFor(m => m.DateOfBirth)
</td>
</tr>
<tr>
<td>Email: </td>
<td>
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(model => model.Email)
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
#Html.TextBoxFor(m => m.Phone)
</td>
</tr>
<tr>
<td>Country: </td>
<td>
#Html.DropDownListFor(m => m.CountryId, Model.Country, new SelectListItem { Value = Model.CountryId.ToString() })
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" id="btnHideModal" /></td>
</tr>
</table>
}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Update</button>
<button type="button" class="btn btn-primary button button4">
Hide
</button>
</div>
<script type="text/javascript">
$(document).ready(function () {
//$("#btnShowModal").click(function () {
$("#loginModal").modal('show');
//});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
----------------------
Edit
---------------------
#model IEnumerable<Practice.Entity.Student>
#{
ViewBag.Title = "Index";
}
<html>
<head>
<script src="~/Scripts/jquery-1.12.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
#*<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/themes/base/jquery-ui.min.css") rel=" stylesheet" type="text/css" />
<script>
$(document).ready(function () {
//$(".editDialog").live("click", function (e) {
$(".editDialog").click(function (e) {
debugger;
var url = $(this).attr('href');
$("#dialog-edit").dialog({
title: 'Edit Employee Detail',
autoOpen: false,
resizable: false,
height: 455,
width: 550,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
debugger;
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$("#dialog-edit").dialog('open');
return false;
});
});
</script>*#
</head>
<body id="divEmp">
<h2>Index</h2>
#Html.ActionLink("Create Student", "Create", "Student")
<div id="dialog-edit">
</div>
<table>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>DOB</td>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.DateOfBirth</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = #item.Id }, new { #class = "editDialog" })*#
<a class="editDialog">Edit</a>
</td>
</tr>
}
</table>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">Satya Login</h4>
<div id="divHtml"></div>
</div>
</div>
</div>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".editDialog").click(function () {
$("#loginModal").modal('show');
$.ajax({
url: '/Student/Edit/1',
contentType: 'application/html; charset=utf-8',
type: 'GET'
})
.success(function (result) {
$('#divHtml').html(result);
})
.error(function (xhr, status) {
alert(status);
});
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
<script>
(function () {
jQuery.fn.szThreeStateColor = function (settings) {
var cfg = {
"overBgColor": "green",
"overFgColor": "white",
"clickBgColor": "blue",
"clickFgColor": "white"
};
if(settings) {
$.extend(cfg, settings);
}
var clickIdx = -1;
$thisObj = $(this);
var iniBgColor = $thisObj.find("tbody td").css("background-color");
var iniFgColor = $thisObj.find("tbody td").css("color");
var iniHeight = $thisObj.find("tr").css("height");
$thisObj.find("tbody tr").bind("mouseover", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": cfg.overBgColor,
"color": cfg.overFgColor
});
}
});
$thisObj.find("tbody tr").bind("mouseout", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
});
$thisObj.find("tbody tr").bind("click", function (e) {
//console.log($(this).index() + ":" + clickIdx);
if($(this).index() != clickIdx) {
if(clickIdx >= 0) {
$thisObj.find("tbody tr:eq(" + clickIdx + ")").css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
$(this).css({
"background-color": cfg.clickBgColor,
"color": cfg.clickFgColor
});
clickIdx = $(this).index();
}
});
return this;
}
})($);
$(document).ready(function () {
$("#table1")
.szThreeStateColor({
"overBgColor": "#34ef2a",
"overFgColor": "#000000",
"clickBgColor": "#333333"
});
$("#table2").szThreeStateColor();
});
</script>
</HEAD>
<BODY>
<table id="table1" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
<table id="table2" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
This plugin sets different cell colors when the events mouseover, mouseout, click are fired. The plugin works fine with a single table but works abnormally when multiple tables are used. Maybe the variable clickIdx is shared by each table. How can I prevent sharing of that variable?
You can do so by wrapping your plugin in return this.each(function() {...}).
jQuery.fn.szThreeStateColor = function (settings) {
// ...
return this.each(function() {
// variables that need to be private go in here
});
}