how to get the checkbox in edit modal popup in MVC-4 - javascript

I'm using ajax to get the corresponding row values in modal popup for edit in MVC 4 razor..
for username textbox i get like this...
#Html.TextBoxFor(u => u.useredit.userName,new { #class = "input-xlarge focused", id="Edituname", type = "text" })
if i use same method for checkbox..
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting plain checkbox.where i gone wrong..or is there any other way for check box,,
Controller:
for getting values through ajax
[HttpPost]
public ActionResult getUserState(int userid)
{
TBLAppUser user = new TBLAppUser();
user = _repository.GetUserByID(userid);
string[] data = new string[10];
data[0] = user.userName;
data[1] = user.firstName;
data[2] = user.lastName;
data[3] = user.email;
data[4] = user.userID.ToString();
data[5] = user.statusID.ToString();
data[6] = user.isdelete.ToString();
data[7] = user.userName;
data[8] = user.password;
data[9] = user.isActive.ToString();
return Json(data);
}
javascript:
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
$('#Edituname').val(data[0]);
$('#Editfname').val(data[1]);
$('#Editlname').val(data[2]);
$('#Editemail').val(data[3]);
$('#Editid').val(data[4]);
$('#state').val(data[5]);
$('#isdelete').val(data[6]);
$('#Editname1').val(data[7]);
$('#Editpsd').val(data[8]);
$('#EditActiv').val(data[9]);
},
error: function (response) {
alert("error:" + response);
}
});
}
view.cshtml:
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting the unchecked checkbox in edit popup..pls smeone help me..thnks in advance...

For your view
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
Make the below changes and see if it working
[HttpPost]
public ActionResult getUserState(int userid)
{
data[9] = user.isActive.ToString()
return Json(data);
}
Try use prop() method
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
var editCheck=(data[9]=== 'true')?true:false;
$('#EditActiv').prop('checked',editCheck); //use prop()
}
});

Related

Passing Javascript Object array to MVC Controller

I have these ViewModels:
public class UserAddRoleListViewModel
{
public String Id { get; set; }
public String Name { get; set; }
}
public class SaveUserNewRoleViewModel
{
[Required]
public String RoleId { get; set; }
public String RoleName { get; set; }
public List<UserAddRoleListViewModel> RoleList { get; set; }
}
How can I pass an array of objects that have a format like this:
var object = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(object);
to my MVC Controller here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyRole(SaveUserNewRoleViewModel Input)
{
IEnumerable<object> errors = null;
if (ModelState.IsValid)
{
if(Input.RoleList[0] != null)
{
foreach (var item in Input.RoleList)
{
if (Input.RoleId == item.Id)
{
ModelState.AddModelError("RoleId", "Role already exists");
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
return Json(new { success = true });
}
return Json(new { success = true });
}
else
{
errors = AjaxError.Render(this);
return Json(new { success = false, errors });
}
}
So far it seems like its always passing an nothing when I debug it
EDIT:
Just to clarify. I can already pass the item via ajax. It's just that when I debug, RoleList is empty.
This is my ajax function:
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = $(this).serializeArray();
form_data.push({ name: "RoleList", value: dataSet });
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
EDIT 2:
Added code that fills dataSet:
$(document).on($.modal.AFTER_CLOSE, function (event, modal) {
dataSet.push(object);
table.row.add(object).draw();
$("#modal").empty();
});
Javascript
$("#myBtn").click(function () {
var dataSet= [];
var obj = {
Id: rowIdItem,
Name: rowItem
};
dataSet.push(obj);
var data = {
"RoleId": '1',
"RoleName ": 'roleName',
"RoleList": dataSet
};
$.ajax({
type: "POST",
traditional:true,
url: "controller/VerifyRole",
content: "application/json;",
dataType: "json",
data: data ,
success: function () {
}
});
});
Controller/Action
[HttpPost]
public ActionResult VerifyRole(SaveUserNewRoleViewModel input)
{
...
}
Try this:)
$(document).on("submit", "#modal", function (e) {
e.preventDefault();
var selectedText = $("##Html.IdFor(m=>m.RoleId) :selected").text();
var selectedId = $("##Html.IdFor(m=>m.RoleId)").val();
var form_data = {};
form_data.RoleId = selectedId;
form_data.RoleName =selectedText;
console.log(form_data);
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
$.ajax({
url: "#Url.Action("VerifyRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (result) {
if (result.success) {
rowIdItem = selectedId;
rowItem = selectedText;
$("#close").trigger("click");
return;
}
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
}
});
return false;
});
my example with datasets:
$("body").on("click", "#btnSave", function () {
var ops = new Array();
$("#table TBODY TR").each(function () {
var row = $(this);
var ps = {};
ps.colname1 = row.find("TD").eq(0).html();
ps.colname2 = row.find("TD").eq(1).html();
ps.colname3= row.find("TD").eq(2).html();
ops.push(ps);
});
var item = {};
item.nam1 = "test";
item.List = ops;
$.ajax({
type: "POST",
url: " ...",
data: JSON.stringify(item),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
}
});
});

Delete record by using ajax from database EntityFramework

I am beginner and trying to delete the record from database by using JavaScript, Ajax and Json in MVC Entity Framework. But my delete button is not working well.
In controller class my action code is
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and my JavaScript code is
<button id='deleteRecord'>delete</button>
$("#deleteRecord").click(function () {
var StudentId = $(this).val();
var stdId = parseInt(StudentId);
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I shall be very thankful if anybody help me.
You need to add your model id in jquery data tag:
<button id='deleteRecord' data-model-id="#model.Id">delete</button>
Then in javascript code:
$("#deleteRecord").click(function () {
var StudentId = $(this).data("model-id");
var url = "/AjaxStudent/Delete/" + StudentId;
$.ajax({
url: url,
type: 'Delete',
}).done(function () {
alert("Deleted")
});
});
}).error(function () {
alert("Failed")
});
I think that the error comes from the type attribute of your ajax call. You assign "delete" to this attribute, but it must be "POST":
$.ajax({
url: "#Url.Action("Delete","AjaxStudent")",
type: "POST", // here is your problem,
data: { StudentId: stdId },
dataType: 'json',
success: function() {
alert("Deleted");
},
error: function(dat) {
alert(data.x);
}
});
And the action method in your controller must be decorated with [httppost] :
[HttpPost]
public JsonResult Delete(int StudentId)
{
using (StudentContext db = new StudentContext())
{
Student std = db.Student.Where(x => x.Id == StudentId).FirstOrDefault<Student>();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
you should try by changing :
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
StudentId: stdId
}
to:
$.ajax({
url: "/AjaxStudent/Delete",
type: 'Delete',
data: {
'id':stdId
}
After lots of time I am able to resolve my problem.
Now my javaScript code
<button class='deleteRecord' data-stid=" + students[i].Id + " >delete</button>
$(".deleteRecord").click(function () {
var StudentId1 = $(this).data("stid");
debugger;
$.ajax({
url: "/AjaxStudent/Delete/" + StudentId1,
type: "Post"
}).done(function () {
getAllStudents();
});
});
});
Controller.cs
public ActionResult Delete(int id) {
using (StudentContext db = new StudentContext()) {
Student std = db.Student.Where(x => x.Id == id).FirstOrDefault();
db.Student.Remove(std);
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}

Cannot pass parameters from View to Controller via JavaScript

Although I manage to send the grid's selected row id to the controller, the url for opening action view cannot be built up (it is created /Controller/Action instead of /Controller/Action/id. So, when I try to open the view with /Controller/Action/id it is open, but it cannot be opened by button click as below.
View:
<input type="button" id="btn" name="name" value="send to Server!" />
<script>
$('#btn').click(function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: item.ID, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")',
success: function (result) {
//console.log(result);
}
})
})
</script>
Controller:
// GET: /Training/CreateParticipant/5
public ActionResult CreateParticipant(int? id)
{
Training training = repository.Trainings.FirstOrDefault(m => m.ID == id);
if (training == null)
{
return HttpNotFound();
}
var trainingParticipantViewModel = new TrainingParticipantViewModel(training);
return View(trainingParticipantViewModel);
}
Route.config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
//defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { controller = "Multiplier", action = "Index", id = UrlParameter.Optional }
);
}
}
Is there another example as above to pass the parameters or is there any mistake on the code above? Thanks in advance.
Javascript
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "GET",
data: item.ID, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")/'+item.ID,
datatype:'html',
success: function (result) {
alert(result)
}
})
})
Or use
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
window.location.href= '#Url.Action("CreateParticipant", "Training")/'+item.ID;
});
Hope this helps.
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
#(Html.Kendo().Button()
.Name("addbtn")
.Content("Add New")
.HtmlAttributes(new { type = "button", #class = "k-primary k-button k-button-icontext js-myKendoButton", #data_id = #Model.YourID, onclick = "onClick()" })
)
</div>
</text>);
})
And then you will grab the data-attribute with jQuery.
$('.js-myKendoButton').attr('data-id');
More here: How to use dashes in HTML-5 data-* attributes in ASP.NET MVC
<script>
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: {ID : item.ID}, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")',
success: function (result) {
//console.log(result);
}
})
})
</script>
use this ,i hope this will be help you

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

JQuery Success Function not firing

I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}
Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}
If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().

Categories

Resources