I will show you all the moving parts involved.
View:
#{
ViewBag.Title = "Partners";
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h1>Partners</h1>
<p>Click to see survey answers or delete partner</p>
<table class="table">
<thead>
<tr>
<th>Partner Name</th><th>Actions</th>
</tr>
</thead>
<tbody>
#foreach ( var NameIdPair in ViewBag.PartnersAndIds )
{
<tr>
<td>
#NameIdPair.Name
</td>
<td>
<button class="btn btn-info view-partner-surveys" data-partnerid="#NameIdPair.Id">View Survey Answers</button>
<button class="btn btn-warning delete-partner" data-partnerid="#NameIdPair.Id">Delete Partner</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#section bottommost {
<script type="text/javascript">
$('.delete-partner').click(function () {
var row = $(this).closest('tr');
$.ajax({
method: 'POST',
url: 'DeletePartner',
data: { pid: $(this).attr('data-partnerid') },
dataType: 'json',
processData: false,
beforeSend: function () {
row.addClass('processing');
},
success: function (retinfo) {
if (retinfo.DeletedSuccessfully) { row.remove(); }
else { alert("Error .."); row.removeClass('processing'); }
},
error: function () { alert("Error"); row.removeClass('processing'); }
});
});
</script>
}
The problem is occuring with the AJAX call invoked with $('.delete-partner').click. The controller handling the request is the simple
[HttpPost]
public ActionResult DeletePartner ( int pid )
{
return Json(new { DeletedSuccessfully = this._Db.DeletePartner(pid) });
}
which used the method DeletePartner in a model defined by
public bool DeletePartner ( int id )
{
SqlCommand cmd = new SqlCommand("DeletePartner", this._Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", id);
this._Conn.Open();
bool succeeded = cmd.ExecuteNonQuery() == 1 ? true : false;
this._Conn.Close();
return succeeded;
}
The sproc its calling is the simple
CREATE PROCEDURE DeletePartner
#id INT
AS
DELETE FROM Partners WHERE id=#id
Any idea where I'm going wrong here?
You should use the url of your ajax call like following.
url: '#Url.Action("DeletePartner")'
You have to give ajax url in the format like
url : '../controllerName/ActionName'
[HttpPost]
public ActionResult DeletePartner ( int pid )
{
return Json(new { DeletedSuccessfully = this._Db.DeletePartner(pid) });
}
The DeletedSuccessfully variable is not recognised by the controller. So it may cause 500 error
Related
I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works. I followed different tutorials but not able to solve it. Please take a look and give me the direction.
Thnx in advance.
Controller
public async Task<IActionResult> dashboard(string sortOrder, string SearchString)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(SearchString))
{
movies = movies.Where(s => s.MovieName.Contains(SearchString));
}
switch (sortOrder)
{
case "name_desc":
movies = movies.OrderByDescending(s => s.MovieName);
break;
default:
movies = movies.OrderBy(s => s.MovieName);
break;
}
return View(await movies.AsNoTracking().ToListAsync());
}
public JsonResult AutoComplete(string prefix)
{
var customers = (from movie in this._context.Movie
where movie.MovieName.StartsWith(prefix)
select new
{
label = movie.MovieName,
val = movie.Id
}).ToList();
return Json(customers);
}
dashboard.cshtml
#model IEnumerable<WebApplication1.Models.Movie>
#{
ViewData["Title"] = "dashboard";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Dashboard</h1>
#using (Html.BeginForm())
{
<p>
Find by Movie Name: #Html.TextBox("SearchString")
<input type="hidden" id="hfCustomer" name="Id" />
<input type="submit" value="Search" />
</p>
}
<table class="table">
<thead>
<tr>
<th>
<a asp-action="dashboard" asp-route-sortOrder="#ViewData["NameSortParm"]">#Html.DisplayNameFor(model => model.MovieName)</a>
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.MovieName)
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#txtMovie").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Movies/AutoComplete/',
data: { "prefix": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works.
Find by Movie Name: #Html.TextBox("SearchString")
If you check the html source code of above TextBox in your browser, you would find it is rendered as below.
The value of id attribute is "SearchString", not "txtMovie". You can try to modify the code to use $("#SearchString") selector, like below.
$("#SearchString").autocomplete({
//...
//code logic here
//...
Test result with testing data
Note: please make sure you add references to required jquery libraries.
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
I am using DataTable library in MVC, but it doesn't work
this is the view Part
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Phone</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Phone</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</tfoot>
</table>
<script type="text/javascript">
//$(document).ready(function () {
// $('#example').DataTable();
//})
$(document).ready(function () {
GetEmployeeRecord();
})
var GetEmployeeRecord = function () {
$.ajax({
type: "Get",
url: "/BasicInfo/GetCustomers",
success: function (response) {
alert("success");
BindDataTable(response);
},
error: function () {
alert("error");
}
})
}
var BindDataTable = function (response) {
$("#example").DataTable({
"aaData": response,
"aoColumns": [
{ "mData": "Id" },
{ "mData": "Phone" },
{ "mData": "FirstName" },
{ "mData": "lastName" }
]
});
}
and this is Controller Part
public JsonResult GetCustomers()
{
SalonEntities db = new SalonEntities();
List<Customer> CustomerList = db.Customers.OrderByDescending(a => a.ID).ToList();
return Json(CustomerList , JsonRequestBehavior.AllowGet);
}
although the CustomerList in controller is loaded but it returns to the view it enters the error section of jquery
what could be the problram
The ajax call to your controller failed. To debug this, you can do two things:
Alert the error
Remove the (dobule quote) " to alert the actual error.
error: function () {
alert(error);
}
You will most probably be able to see it in developer tools in your console.
Check the network tab
In your network tab, you'll see the error (4XX, 5XX) or something like that with some extra information (if you are lucky).
If no more information is there and you have an error 500, you need to check the exception in your backend code.
I have a log in controller and a view. Whenever I click the log in button I check if the password given is correct and I used Redirect To Action to redirect to my home page. But, whenever I get to that page the page is not showing. What am I doing wrong???
In firebug it shows
GET http://localhost:64703/Home Page
should it be POST?
Javascript:
$('#Login').on('click', function () {
var model = {};
model["model.Password"] = $('#Password').val();
$.ajax({
url: '#Url.Action("Login", "LogIn")',
type: "POST",
data: model,
success: function (response) {
},
error: function (response) {
}
});
});
View:
<div >
<div >
#Html.ValidationSummary(true)
<table style="margin-top: 10px;">
<tr>
<td >
#Html.LabelFor(model => model.Password)
</td>
<td >
#Html.PasswordFor(model => model.Password)
</td>
</tr>
<tr>
<td colspan="2">
<label id="errorMsg" class="calibri">
</label>
</td>
</tr>
</table>
<input type="button" id="Login" value="Login" />
</div>
</div>
Controller:
[HttpPost]
public ActionResult Login(LogIn model)
{
try
{
EntityConnection connection = connect.getConnection();
Entities ctx = new Models.Entities(connection);
connection.Open();
connection.Close();
return RedirectToAction("Index", "HomePage");
}
catch (Exception ex)
{
return Json(ex);
}
}
Here is my Code.. Please let me know what should be done and what should not be done. Thanks in advance.
Change only your jquery code, redirect the page:
success: function (response) {
alert("if this test dialog appears, so page will redirect");
//just add this line:
window.location.href = '#Url.Action("Index", "HomePage")';
},
I think, on basis what you have posted, that there is either not a Controller or Action which matches:
Controller: HomePage
Action: Index
See the explanation of the RedirectToAction method.
You are using ajax to make the login request.
As such, you need to update your ajax response handlers to allow the page to redirect.
$('#Login').on('click', function () {
var model = {};
model["model.Password"] = $('#Password').val();
$.ajax({
url: '#Url.Action("Login", "LogIn")',
type: "POST",
data: model,
success: function (response) {
// Check for login is successful
if (response.LoginResult == true) window.location = response.Redirect;
else alert("Login failed.");
},
error: function (response) {
}
});
});
// Controller
[HttpPost]
public ActionResult Login(LogIn model)
{
try
{
EntityConnection connection = connect.getConnection();
Entities ctx = new Models.Entities(connection);
connection.Open();
connection.Close();
if (true) // Logic to validate login
{
return Json(new { LoginResult = true, Redirect = RedirectToAction("Index", "HomePage") });
}
return Json(new { LoginResult = false });
}
catch (Exception ex)
{
return Json(ex);
}
}
The above sample fuzzies over the login logic - so use whatever logic you currently have.
The core concept is that the controller should return a json object that the client can evaluate and determine what to do. Be aware that the success function will be triggered even if your login logic is incorrect - as long as there was no error by the server.
Apologies if this i trivial, i have read many other comments and still cannot see what is wrong. I have done a few tutorials and they seem to work ok, so I am really missing something simple.
I have a basic 'remove' link that i want to do a JQuery Post back to the controller to remove an item from the database and then update the view.
My View / Javascript:
<script type="text/javascript">
$(function () {
$(".RemoveLink").click(function () {
var id = $(this).attr("data-id");
if (id != '') {
$.post("#Url.Content("~/Agent/Remove")", { "id": id }, function (data) { alert('Here i am'); });
}
});
});
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.ID" >Remove</a>
</td>
</tr>
}
My Controller:
[HttpPost]
public ActionResult Remove(int id)
{
return Json(new { Data = "true" });
}
Any assistance will be great.
Use #Url.Action("Remove", "Agent") instead.
#Url.Content("...") is used to locate any static content of the site.
Cheers
Below code works well.
#foreach (var item in Model.Object) {
<tr id="row-#item.ID">
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<input type="button" class="RemoveLink" id="#item.ID" Value="Remove" />
</td>
</tr>
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('.RemoveLink').live("click", function () {
Remove($(this));
});
});
function Remove(_this) {
var Id= $(_this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("Remove", "Agent")',
data: "{id: '" + Id + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
//do something here......
},
error: function () {
}
});
}
</script>
Context:
Hello, I'm developing an on line application of Tennis Club Management... I would like to create an "Available Tennis Court Interface" that allows the user to check if a court is busy or free... So in my Interface I have one DatePicker, an image "Google Maps" of the Tennis Club and 13 labels that represents all tennis courts. So in this interface, if a tennis court is busy, I would like to "color" the label in red and if the tennis court is free, in green...
Here my Interface:
Code
For that, I'm using Jquery, JavaScript and Json... Here what I have tried to make in my View :
<script type="text/javascript">
function loadCourts() {
var maDate = $('#datePicker').val();
$.post({
type: 'POST',
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
data: "{ 'date' : " + maDate + " }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
alert('test');
//How to use data and verify if a tennis is free or not ?
},
error: function(x, t, m) {
if (t === "timeout") {
window.HandleTimeout();
} else {
alert(t);
}
}
});
}
</script>
<h2>Emplacement(s) disponible(s)</h2>
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(chargerCourts());
});
</script>
//Here the label
<div class="AvailableCourt">
<div class="label1" align="center">
#Html.Label("1")
</div>
<div class="label2" align="center">
#Html.Label("2")
</div>
<div class="label2" align="center">
#Html.Label("3")
</div>
<div class="label2" align="center">
#Html.Label("4")
</div>
<div class="label3" align="center">
#Html.Label("5")
</div>
<div class="label4" align="center">
#Html.Label("6")
</div>
<div class="label5" align="center">
#Html.Label("7")
</div>
<div class="label6" align="center">
#Html.Label("8")
</div>
<div class="label7" align="center">
#Html.Label("9")
</div>
<div class="label8" align="center">
#Html.Label("10")
</div>
<div class="label9" align="center">
#Html.Label("11")
</div>
<div class="label10" align="center">
#Html.Label("12")
</div>
<div class="label11" align="center">
#Html.Label("13")
</div>
}
</div>
Controller method
//Get all the tennis courts and verify if a court is busy or not (Available attribute)
public JsonResult GetTennisCourt(DateTime date)
{
System.Diagnostics.Debug.WriteLine("test");
var reservations = db.Reservations.Include(c => c.Customer);
foreach (var reservation in reservations)
{
//Verify that a court is available or not
if (reservation.Date ==date)
{
if (date.Hour > reservation.FinishTime.Hour || date.Hour < reservation.StartTime.Hour)
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(t => t.ID == id);
tennisCourt.Available = true;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
}
else
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(s => s.ID == id);
tennisCourt.Available = false;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
break;
}
}
}
var courts = from c in db.TennisCourts
select c;
courts = courts.OrderBy(c => c.ID);
System.Diagnostics.Debug.WriteLine("test");
return Json(courts, JsonRequestBehavior.AllowGet );
}
When I'm using Firebug, I get an error in my function "loadCourts" and so my controller's method (getTennisCourts) is never reaches) I don't understand why:
Questions
So, my questions are :
1) Why get I an error in Firebug ?
2) Why is my Controller's method never reaches ?
3) How could I use "data" in my function "loadCourts" to check if a tennis court is free or not ?
Sorry for the length and thanks in advance...
For Darin Dimitrov :
Try like this:
// get the underlying Date object from the datepicker instead
// of using .val()
var maDate = $('#datePicker').datepicker('getDate');
$.ajax({
type: 'POST',
url: '#Url.Action("GetTennisCourt", "AvailableCourt")',
data: '{ "date":"\\/Date(' + maDate.getTime() + ')\\/" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
// we loop through the collection of courts
// returned by the server and we can access each
// element's properties
$.each(data, function(index, court) {
alert(court.ID);
});
},
error: function(x, t, m) {
if (t === 'timeout') {
window.HandleTimeout();
} else {
alert(t);
}
}
});
Notice that I used $.ajax instead of $.post. And I have used the datepicker's getDate method to fetch the native Date object and encode it.
I dont know C# but this line:
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
Is resolving the url as an object, if you had
url : '/path/to/controller'
It might work
The 'data' in the success function is JSON so you can treat it as an object.
data.xyz