update model with ajax in razor - ajax

i write this code with ajax to delete some info after that i update my updateAjax div with ajax for refreshing content and this view have masterpage.in picture u see what happen.
this is my code
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
<div class="btnContainer">
delete
<br />
<br />
</div>
<script>
$(function () {
// function for delet info and update #updateAjax div
$("#DeleteUser").click(function (event) {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
$.ajax({
url: '#Url.Action("DeleteUser", "UserManagement")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: JSON.stringify(list),
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
// window.location.reload()
},
error: function (data) {
//$('#updateAjax').html(data);
window.location.reload()
}
}); //end ajax
});});
</script>
</form>
this my controller code
public ActionResult View1()
{
ViewBag.PageTittle = "user list";
ViewBag.FormTittle = "user list";
SetUserManagement();
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(Result.Data);
}
else
{
return View(new VwUser());
}
}
public ActionResult DeleteUser(string[] userId)
{
SetUserManagement();
string message = "", CssClass = ""; ;
foreach (string item in userId)
{
//TODO:show Message
var Result = userManagement.DeleteUser(int.Parse(item));
if (Result.Mode != Common.Extensions.ActionResultMode.Successfully)
{
var messageResult = XmlReader.FindMessagekey(Result.Mode.ToString());
message += messageResult.MessageContent + "<br/>";
CssClass = messageResult.cssClass;
}
}
if (string.IsNullOrEmpty(message))
{
SetMessage(Common.Extensions.ActionResultMode.Successfully.ToString());
}
else
{
ViewBag.MessageResult = message;
ViewBag.cssClass = CssClass;
}
//
{
var Result = userManagement.SearchUsers(null);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View("~/Views/UserManagement/View1.cshtml", Result.Data);
}
else
{
return View("~/Views/UserManagement/View1.cshtml", new VwUser());
}
}
}

It looks to me that your view ViewUserList.cshtml is using a Layout that would either be set through Layout or through the _ViewStart.cshtml file. Make sure you're not using any of these.
For disabling the use of your Layout, you could take a look at this question. Or just set Layout = null

Related

Kendo-Knockout reference with MVC using Database First Approach [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am looking for Kendo-Knockout reference with MVC using Database First Approach.
Please look at my code below,
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.Category = ko.observable();
self.Price = ko.observable();
var Product = {
Id: self.Id,
Name: self.Name,
Category: self.Category,
Price: self.Price
};
self.Product = ko.observable();
self.Products = ko.observableArray();
$.getJSON("/Product/GetProoducts", function (data) {
self.Products(data);
$.each(data, function (index) {
})
});
self.Create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.push(data);
self.Name("");
self.Price("");
self.Category("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
}
ko.applyBindings(new ViewModel());
});
I am getting an issue with the above code. I need to do CRUD operation using kendo - knockout js.
Please find below code ,
Repository
interface IProductRepository : IDisposable
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
void Save();
}
public class ProductRepository : IProductRepository, IDisposable
{
RepositoryEntities context = null;
public ProductRepository()
{
context = new RepositoryEntities();
}
public ProductRepository(RepositoryEntities context)
{
this.context = context;
}
public IEnumerable<Product> GetAll()
{
return context.Products.ToList();
}
public Product Get(int id)
{
return context.Products.Find(id);
}
public Product Add(Product item)
{
Product newProduct = context.Products.Add(item);
int id = context.SaveChanges();
return newProduct;
}
public bool Update(Product item)
{
context.Entry(item).State = EntityState.Modified;
context.SaveChanges();
return true;
}
public bool Delete(int id)
{
Product objProduct = context.Products.Find(id);
context.Products.Remove(objProduct);
context.SaveChanges();
return true;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Controller
public class ProductController : Controller
{
// private IProductRepository productRepository;
private IProductRepository repository = new ProductRepository();
//public ProductController(IProductRepository repository)
//{
// this.productRepository = repository;
//}
//
// GET: /Product/
public ActionResult Index()
{
return View();
}
public JsonResult GetProoducts()
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
public JsonResult AddProduct(Product item)
{
item = repository.Add(item);
return Json(item, JsonRequestBehavior.AllowGet);
}
public JsonResult EditProduct(int id, Product product)
{
product.Id = id;
if (repository.Update(product))
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
return Json(null);
}
public JsonResult DeleteProduct(int id)
{
if (repository.Delete(id))
{
return Json(new { Status = true }, JsonRequestBehavior.AllowGet);
}
return Json(new { Status = false }, JsonRequestBehavior.AllowGet);
}
}
View
#{
ViewBag.Title = "Index";
}
<script src="~/jquery.min.js"></script>
<script src="~/kendo.all.min.js"></script>
<script src="~/knockout-3.1.0.js"></script>
<script src="~/knockout-kendo.min.js"></script>
<link href="~/kendo.silver.min.css" rel="stylesheet" />
<div id="body">
<h2>Kendo Knockout CRUD Operations</h2>
<div data-bind="kendoGrid: { data : Products, rowTemplate: 'rowTmpl', scrollable: true, sortable: true, useKOTemplates: true}">
</div>
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Name"></td>
<td data-bind="text: Price"></td>
<td data-bind="text: Category"></td>
<td> <button data-bind="click: $root.Edit">Edit</button></td>
<td> <button data-bind="click: $root.Delete">Delete</button></td>
</tr>
</script>
<br/>
<div data-bind="if: Product">
<div>
<h2>Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">ID</label>
<label data-bind="text: Product().Id, visible: false"></label>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.Update">Update</button>
<button data-bind="click: $root.Cancel">Cancel</button>
</div>
</div>
<br />
<div data-bind="ifnot: Product()">
<div>
<h2>Add New Product</h2>
</div>
<div>
<label for="name">Name</label>
<input data-bind="value: $root.Name" type="text" title="Name" />
</div>
<div>
<label for="price">Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<div>
<label for="category">Category</label>
<input data-bind="value: $root.Category" type="text" title="Category" />
</div>
<div>
<button data-bind="click: $root.Create">Save</button>
<button data-bind="click: $root.Reset">Reset</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var ViewModel = function () {
var self = this;
self.Id = ko.observable();
self.Name = ko.observable();
self.Category = ko.observable();
self.Price = ko.observable();
var Product = {
Id: self.Id,
Name: self.Name,
Category: self.Category,
Price: self.Price
};
self.Product = ko.observable();
self.Products = ko.observableArray();
$.getJSON("/Product/GetProoducts", function (data) {
self.Products(data);
$.each(data, function (index) {
})
});
self.Create = function () {
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.push(data);
self.Name("");
self.Price("");
self.Category("");
}
}).fail(function (xhr, textStatus, err) {
alert(err);
});
}
}
self.Reset = function () {
self.Name("");
self.Price("");
self.Category("");
}
// Edit product details
self.Edit = function (Product) {
self.Product(Product);
}
// Cancel product Details
self.Cancel = function () {
self.Product(null);
}
//Update Product Details
self.Update = function () {
var Product = self.Product();
$.ajax({
url: '#Url.Action("EditProduct", "Product")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Product),
success: function (data) {
self.Products.removeAll();
self.Products(data); //Put the response in ObservableArray
self.Product(null);
alert("Record Updated Successfully");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
}
//Delete Product Details
self.Delete = function (Product) {
if (confirm('Are you sure to Delete "' + Product.Name + '" product ??'))
{
var id = Product.Id;
$.ajax({
url: '/Product/DeleteProduct/'+ id,
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(id),
success: function (data) {
self.Products.remove(Product);
}
}).fail(
function (xhr, textStatus, err) {
self.status(err);
});
}
}
}
ko.applyBindings(new ViewModel());
});
</script>
Please find below links too,
http://www.dotnet-tricks.com/Tutorial/knockout/0bOU010413-Knockout-CRUD-Operations-using-MVC4.html
http://pinaki-mukherjee.blogspot.in/2013/01/kendo-knockout-grid-bind.html
http://www.c-sharpcorner.com/uploadfile/yusufkaratoprak/asp-net-mvc-with-knockout-js/
http://www.codeproject.com/Articles/640294/Learning-MVC-Part-Generic-Repository-Pattern-in

ASP.NET MVC3: Ajax postback doesnot post complete data from the view

Hi Greetings for the day!
(1) The view model (MyViewModel.cs) which is bound to the view is as below...
public class MyViewModel
{
public int ParentId { get; set; } //property1
List<Item> ItemList {get; set;} //property2
public MyViewModel() //Constructor
{
ItemList=new List<Item>(); //creating an empty list of items
}
}
(2) I am calling an action method through ajax postback (from MyView.cshtml view) as below..
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {$('#MyForm').html(html);}
});
}
The below button click will call the ajax postback...
<input type="button" value="Add" class="Previousbtn" onclick="AddItem()" />
(3) I have an action method in the (MyController.cs controller) as below...
public ActionResult AddItem(MyViewModel ViewModel)
{
ViewModel.ItemList.Add(new Item());
return View("MyView", ViewModel);
}
Now the issue is, after returning from the action, there is no data in the viewmodel. But i am able to get the data on third postback !! Can you pls suggest the solution..
The complete form code in the view is below...
#model MyViewModel
<script type="text/javascript" language="javascript">
function AddItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/AddItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function RemoveItem() {
var form = $('#MyForm');
var serializedform = form.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/RemoveItem")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
function SaveItems() {
var form = $('#MyForm');
var serializedform = forModel.serialize();
$.ajax({
type: 'POST',
url: '#Url.Content("~/MyArea/MyController/SaveItems")',
cache: false,
data: serializedform,
success: function (html) {
$('#MyForm').html(html);
}
});
}
</script>
#using (Html.BeginForm("SaveItems", "MyController", FormMethod.Post, new { id = "MyForm" }))
{
#Html.HiddenFor(m => Model.ParentId)
<div>
<input type="button" value="Save" onclick="SaveItems()" />
</div>
<div>
<table>
<tr>
<td style="width: 48%;">
<div style="height: 500px; width: 100%; overflow: auto">
<table>
<thead>
<tr>
<th style="width: 80%;">
Item
</th>
<th style="width: 10%">
Select
</th>
</tr>
</thead>
#for (int i = 0; i < Model.ItemList.Count; i++)
{
#Html.HiddenFor(m => Model.ItemList[i].ItemId)
#Html.HiddenFor(m => Model.ItemList[i].ItemName)
<tr>
#if (Model.ItemList[i].ItemId > 0)
{
<td style="width: 80%; background-color:gray;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%; background-color:gray;">
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
#Html.HiddenFor(m => Model.ItemList[i].IsSelected)
</td>
}
else
{
<td style="width: 80%;">
#Html.DisplayFor(m => Model.ItemList[i].ItemName)
</td>
<td style="width: 10%">
#if ((Model.ItemList[i].IsSelected != null) && (Model.ItemList[i].IsSelected != false))
{
<img src="#Url.Content("~/Images/tick.png")" alt="Added"/>
}
else
{
#Html.CheckBoxFor(m => Model.ItemList[i].IsSelected, new { #style = "cursor:pointer" })
}
</td>
}
</tr>
}
</table>
</div>
</td>
<td style="width: 4%; vertical-align: middle">
<input type="button" value="Add" onclick="AddItem()" />
<input type="button" value="Remove" onclick="RemoveItem()" />
</td>
</tr>
</table>
</div>
}
You must return PartialViewResult and then you can do something like
$.post('/controller/GetMyPartial',function(html){
$('elem').html(html);});
[HttpPost]
public PartialViewResult GetMyPartial(string id
{
return PartialView('view.cshtml',Model);
}
In my project i get state data with country id using json like this
in my view
<script type="text/javascript">
function cascadingdropdown() {
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
alert(data);
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
in my controller return data in json format
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
i think this will help you ....
I resolved the issue as below...
Issue:
The form code i have shown here is actually part of another view page
which also contains a form. So, when i saw the page source at
run-time, there are two form tags: one inside the other, and the
browser has ignored the inner form tag.
Solution:
In the parent view page, earlier i had used Html.Partial to render
this view by passing the model to it.
#using(Html.BeginForm())
{
---
---
#Html.Partial('/MyArea/Views/MyView',MyViewModel)
---
---
}
But now, i added a div with no content. On click of a button, i'm
calling an action method (through ajax postback) which then renders
the above shown view page (MyView.cshmtl) into this empty div.
#using(Html.BeginForm())
{
---
---
<div id="divMyView" style="display:none"></div>
---
---
}
That action returns a separate view which is loaded into the above
div. Since it is a separate view with its own form tag, i'm able to
send and receive data on each postback.
Thank you all for your suggestions on this :)

partial view refresh using jQuery

On my main edit view I have 3 partial views that contain child data for the main view model. I also have html text boxes for entering and saving related data such as notes etc.
After an item is entered or select and passed to a controller action, how do I refresh my partial views? Here is the code I have so far but it does not work. I think I need to pass a model back with my partial view?
I am using ajax to call my controller method.
Partial View:
#model cummins_db.Models.CaseComplaint
<table width="100%">
<tr>
<td>
#Html.DisplayFor(modelItem => Model.ComplaintCode.ComplaintCodeName)
</td>
<td>
#Html.DisplayFor(modelItem => Model.ComplaintCode.ComplaintType)
</td>
</tr>
</table>
This is the html where the partial view is located:
<div class="editor-label">
#Html.Label("Search and select a complaint code")
</div>
<div class="textarea-field">
<input id = "CodeByNumber" type="text" />
</div>
#Html.ActionLink("Refresh", "Edit", new { id = Model.CasesID })
<table width="100%">
<tr>
<th>Complaint Code</th>
<th>Complaint Description</th>
</tr>
#try
{
foreach (var comp_item in Model.CaseComplaint)
{
<div id="complaintlist">
#Html.Partial("_CaseComplaintCodes", comp_item)
</div>
}
}
catch
{
}
</table>
Here is the controller method that returns the partial view.
public ActionResult SelectForCase(int caseid, int compid, string compname)
{
if (ModelState.IsValid)
{
CaseComplaint c = new CaseComplaint
{
CasesID = caseid,
ComplaintCodeID = compid
};
db.CaseComplaints.Add(c);
db.SaveChanges();
}
return PartialView("_CaseComplaintCodes");
}
jQuery ajax calling the controller, it is part of an autocomplete function select.
$('#CodeByNumber').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Cases/CodeByNumber", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.ComplaintType,
value: item.ComplaintCodeName,
id: item.ComplaintCodeID
}; //return
}) //map
); //response
} //success
}); //ajax
}, //source
select: function (event, ui) {
var url = "/Cases/SelectForCase";
$.ajax({
type: "GET",
dataType: "html",
url: url,
data: { caseid: $('#CaseID').val(), compid: ui.item.id, compname: ui.item.label },
success: function (result) { $('#complaintlist').html(result); }
});
},
minLength: 1
});
Should the partial view not be as below:
#model cummins_db.Models.CaseComplaint
<table width="100%">
<tr>
<td>
#Html.DisplayFor(m => m.ComplaintCodeName)
</td>
<td>
#Html.DisplayFor(m => m.ComplaintType)
</td>
</tr>
</table>
This is what I ended up doing to make it work. I changed by controller action to this:
public ActionResult SelectForCase(int caseid, int compid)
{
if (ModelState.IsValid)
{
CaseComplaint c = new CaseComplaint
{
CasesID = caseid,
ComplaintCodeID = compid
};
db.CaseComplaints.Add(c);
db.SaveChanges();
var m = from d in db.CaseComplaints
where d.CasesID == caseid
select d;
return PartialView("_CaseComplaintCodes", m);
}
return PartialView("_CaseComplaintCodes");
}
It works now

How do i fire validation message on Button click instead of Submit button

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>

Using jQuery and ASP.NET MVC together. Ajax post is not working?

I have a form submit with an AJAX post. It works fine.
But when I delete the item by clicking the delete link, I have an issue, a get request not post.
But from my javascript function, you can see I use jQuery css selctor to detect the link clicked or not, so I am confused.
Here is my code
My controller:
public class SessionsController : Controller
{
private SessionRepository _repository;
public SessionsController() : this(new SessionRepository()) { }
public SessionsController(SessionRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
var sessions = _repository.FindAll();
//for ajax requests, we simply need to render the partial
if (Request.IsAjaxRequest())
return PartialView("_sessionList2", sessions);
//return View("_sessionList", sessions);
return View(sessions);
}
[HttpPost]
public ActionResult Add(Session session)
{
_repository.SaveSession(session);
if (Request.IsAjaxRequest())
return Index();
return RedirectToAction("index");
}
[HttpPost]
public ActionResult Remove(Guid session_id)
{
_repository.RemoveSession(session_id);
return RedirectToAction("index");
}
}
The session view:
#model IEnumerable<MyMVCDemo.Models.Session>
<h2>Hijax Technique</h2>
<div id="session-list">
#{Html.RenderPartial("_sessionList2");}
</div>
<p>
</p>
#using (Html.BeginForm("add", "sessions", FormMethod.Post, new { #class = "hijax" }))
{
<fieldset>
<legend>Propose new session</legend>
<label for="title">Title</label>
<input type="text" name="title" />
<label for="description">Description</label>
<textarea name="description" rows="3" cols="30"></textarea>
<label for="level">Level</label>
<select name="level">
<option selected="selected" value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
</select>
<br />
<input type="submit" value="Add" />
<span id="indicator" style="display:none"><img src="../../content/load.gif" alt="loading..." /></span>
</fieldset>
}
<label>
<input type="checkbox" id="use_ajax" />
Use Ajax?
</label>
<script src="../../Scripts/Common.js" type="text/javascript"></script>
My Partial View:
#model IEnumerable<MyMVCDemo.Models.Session>
<table id="sessions">
<tr>
<th>Title</th>
<th>Description</th>
<th>Level</th>
<th></th>
</tr>
#if(Model.Count() == 0) {
<tr>
<td colspan="4" align="center">There are no sessions. Add one below!</td>
</tr>
}
#foreach (var session in Model)
{
<tr>
<td>#session.Title</td>
<td>#session.Description</td>
<td>session.Level</td>
<td>
#Html.ActionLink("remove", "remove", new { session_id = session.Id }, new { #class = "delete" })
</td>
</tr>
}
This is my javascript which call the ajax post:
$('.delete').click(function () {
if (confirm('Are you sure you want to delete this item?')) {
$.ajax({
url: this.href,
type: 'POST',
success: function (result) {
$("#session-list").html(result);
}
});
return false;
}
return false;
});
$("form.hijax").submit(function (event) {
if ($("#use_ajax")[0].checked == false)
return;
event.preventDefault(); //prevent the actual form post
hijack(this, update_sessions, "html");
});
function hijack(form, callback, format) {
$("#indicator").show();
$.ajax({
url: form.action,
type: form.method,
dataType: format,
data: $(form).serialize(),
completed: $("#indicator").hide(),
success: callback
});
}
function update_sessions(result) {
//clear the form
$("form.hijax")[0].reset();
//update the table with the resulting HTML from the server
$("#session-list").html(result);
$("#message").hide().html("session added")
.fadeIn('slow', function () {
var e = this;
setTimeout(function () { $(e).fadeOut('slow'); }, 2000);
});
}
It looks to me like you do not rebind the click event after you update the partial.
What happends is that you replace the DOM(which the events are bound to) when you make the ajax call. So after you update post the form all your events are gone.
In jquery there is a live event that would help you here.
The code below is not tested some there might be some problems with it but it should give you an idea.
var sessionList = $('#session-list');
$('.delete', sessionList).live('click', function () {
if (confirm('Are you sure you want to delete this item?')) {
$.ajax({
url: this.href,
type: 'POST',
success: function (result) {
sessionList.html(result);
}
});
return false;
}
return false;
});
The selector $('.delete', sessionList) is to give the live function a context so it doesn't bubble events all the way to the top.

Resources