Unable to save data using jquery which is lengthy - javascript

I have a textareafor
<div class="inner-addon left-addon">
Html.TextAreaFor(m => m.DataFixes, new { #class = "resizedTextbox", id = "txtDataFixes", placeholder = "Data Fixes" , style = "width : 70px,height : 70px;" })
</div>
I have used jquery to save the data using the button click. When i click on the save button then iam able to save the data in the textbox for when the data entered is small, But when i try to save a lengthy data, it doesnot get saved. The below is my jquery code. I think it has something to do with the var object.
$('#btnUpdateDataSet').click(function() {
var note = $("#txtNote").val();
var fileContentName = $("#txtFileContentName").val();
var fileContentId = $("#fileContentId").val();
var dataFixes = $("#txtDataFixes").val();
var oldWorkitemId = $('#drpOldWorkitemId option:selected').val();
if (fileContentName.length == 0) {
var fileContentId = null;
} else {
var fileContentId = $("#fileContentId").val();
}
updateDataSet(workItemID, dataSetDateStamp, cycle, reference, feed, source, target, lineStart, extension, note, fileContentId, dataFixes, oldWorkitemId);
});
The below is my controller
public ActionResult EditDataSet( string dataFixes)
{
EditDataSetVM editDataSetVM = new EditDataSetVM();
editDataSetVM.DataFixes = dataFixes;
return PartialView("EditDataSetView", editDataSetVM);
}
My Ajax call
function updateDataSet(workItemID, dataSetDateStamp, cycle, reference, feed, source, target, lineStart, extension, note, fileContentId, dataFixes,oldWorkitemId) {
$.ajax({
type: "POST",
url: "/DataSet/UpDateDataSetDetails",
contentType: "application/json; charset=utf-8",
data: { "workItemId": workItemID, "dataSetDateStamp":
dataSetDateStamp, "cycle": cycle, "reference": reference, "feed": feed, "source": source, "target": target, "lineStart": lineStart, "extension":
extension, "note": note, "fileContentId": fileContentId, "dataFixes":
dataFixes, "oldWorkitemId": oldWorkitemId },
datatype: "json",
success: function (data) {
if (data == "Update Succeeded") {
$("#btnViewDataSet").click();
}
else {
$("div.toshow").show();
$('#lblUpdateDataSetResult').html('Following error(s) occured:<br\>' + data);
}
},
error: function () {
alert("Update WorkItem metadata failed.");
}
});
}

Related

How do i use a custom button to send to the JQGrid's editurl?

I have the below custom button added to my navigation pager, but i want it to look at what i multi selected and send it to the JQGrid's editurl for processing which is a ASHX.CS page
But i can't make sense of the documentation when it comes to custom button
I can get it call a local function with onClickButton: customButtonClicked but it doesn't send the data like the EDIT button does
In the end what i want to do it select multiple rows and press a button on the navbar and approve all the selected records
// add first custom button
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
editData: {
WrkId: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
}
return value;
},
CurrentUser: function () {
return '<% =System.Web.HttpContext.Current.User.Identity.Name %>';
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#jQGrid").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
}
}
);
using a few different words (how to manually post data to server json) i was able to find a snippet of an ajax code that made more sense (i'm sure i came across this before but as someone who has no jquery experience i didn't recognize it)
but the below sends to the C# handler page the data in a JSON string that was processable, had to use dynamic to read it in but it worked, couldn't get it to not return an error even though there was no error, so i used the complete: instead of success: and then called the trigger to reload the JQGrid
Final Code:
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-check",
title: "Approve all selected entries",
caption: "Approve",
position: "last",
onClickButton: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
};
$.ajax({
type: "POST",
url: "AdministrationHandler.ashx?oper=approve",
data: JSON.stringify({
WrkId: value,
CurrentUser: "<% =System.Web.HttpContext.Current.User.Identity.Name %>"
}),
dataType: "json",
contentType: "application/json; charsset=utf-8",
complete: function (xhr, x) {
if (xhr.responseText.toUpperCase().indexOf("SUCCESS") >= 0) {
alert('Success!\n' + xhr.responseText);
}
else {
alert('Failed!\n' + xhr.responseText + '\n' + x);
};
$("#jQGrid").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
})
}
});
C# Code
try
{
String postData = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
var data = JsonConvert.DeserializeObject<dynamic>(postData);
Approve(data.WrkId.ToString(), data.CurrentUser.ToString());
strResponse = "Employee records successfully approved";
}
catch
{
strResponse = "Employee records not approved";
}
context.Response.Write(strResponse);

Retrieving event and htmlInput element from a foreach using javascript or jquery

I managed to retrieve a dynamic element ID from inside a foreach and send it to a controller this way:
#using (Html.BeginForm("DeleteConfirmed", "Gifts", FormMethod.Post, new { #class = "form-content", id = "formDiv" }))
{
foreach (var item in Model.productList)
{
<input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" />
}
}
and here's the relevant script, pointing to the controller's ActionResult method in charge for item deletion:
function DeleteButtonClicked(elem) {
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
window.location.href = "/Gifts/DeleteConfirmed/" + itemID;
}}
Now, this works just fine, as itemID is correctly retrieved.
As I would like to add a #Html.AntiForgeryToken() to the form, the idea is to change the MVC controller's Actionmethod into a JsonResult adding a little Ajax to the script, allowing me to pass both itemID and token.
Something like:
function DeleteButtonClicked(elem) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(elem).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
dynamic }Some
but I have no idea on how to add the 'event' to the element (this => elem) in <input type="button" value="Delete" onclick="DeleteButtonClicked(this)" data-assigned-id="#item.ID" /> that I am using to identify the item inside the foreach loop, in order to pass it to the script.
Above script obviously fails as there's no 'event' (provided this would end to be the only mistake, which I'm not sure at all).
Some help is needed. Thanks in advance for your time and consideration.
What you want to do is use jQuery to create an event handler:
$('input[type="button"]').on('click', function(event) {
event.preventDefault();
var form = $('#formDiv');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var itemID = $(this).data('assigned-id');
if (confirm('sure?')) {
$.ajax({
type: 'POST',
datatype: 'json',
url: '#Url.Action("DeleteConfirmed", "Gifts")',
data: {
__RequestVerificationToken: token,
id: itemID
},
cache: false,
success: function (data) { window.location.href = "/Gifts/UserProfile?userID=" + data; },
error: function (data) { window.location.href = '#Url.Action("InternalServerError", "Error")'; }
});
}
});
Just make sure you render this script after your buttons are rendered. Preferably using the $(document).onReady technique.
Try the 'on' event handler attachment (http://api.jquery.com/on/). The outer function is shorthand for DOM ready.
$(function() {
$('.some-container').on('click', '.delete-btn', DeleteButtonClicked);
})

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().

Adding Item to list on click Javascript/Jquery

So i have list that is created dynamically as shown
Now I need a ADD button, which on click will add new item to list automatically. Help me out with this please.
Hi this is how can you retrive data using jquery
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "URL/MethodName",
data: "{}",// you can provide parameteres to your function here
dataType: "JSOn",
success: function (data) {
for (var i in data) {
alert(data[i].Id); //assign to controls
alert(data[i].Header);// assign to controls
alert( data[i].Content) ;// assign to contols
}
alert('Data fetched Successfully');
},
error: function (result) {
alert('Data not fetched ');
return false;
}
});
return false;
});
/*************************************************************************
[System.Web.Services.WebMethod]
public ActionResult Careers()
{
List<JobOpening> job = new List<JobOpening>()
{
new JobOpening{Id = 1, Header = "Job1", Content = "edde" },
new JobOpening{Id = 2,Header = "Job2", Content = "deded" },
};
}

Prevent redirecting after saving post in blogengine

I am using BlogEngine as my blogging platform and I would like to know if there is a way to prevent the post redirect action after I am saving my post, I tried to debug the code but couldn't find the redirect action.
this is the save post method in the client side:
function SavePost() {
$('.loader').show();
var content = document.getElementById('<%=txtRawContent.ClientID %>') != null ? document.getElementById('<%=txtRawContent.ClientID %>').value : tinyMCE.activeEditor.getContent();
var title = document.getElementById('<%=txtTitle.ClientID %>').value;
var slug = document.getElementById('<%=txtSlug.ClientID %>').value;
var photo = document.getElementById('<%=txtPostPhoto.ClientID %>').value;
var kind = $("[id$='ddlKind'] option:selected").val();
var isPublished = $("[id$='cbPublish']").is(':checked');
var date = document.getElementById('<%=txtDate.ClientID %>').value;
var time = document.getElementById('<%=txtTime.ClientID %>').value;
var dto = {
"id": Querystring('id'),
"content": content,
"title": title,
"slug": slug,
"postPhoto": photo,
"kind": kind,
"isPublished": isPublished,
"date": date,
"time": time
};
//alert(JSON.stringify(dto));
$.ajax({
url: SiteVars.ApplicationRelativeWebRoot + "admin/AjaxHelper.aspx/SaveMiniPost",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dto),
beforeSend: onAjaxBeforeSend,
success: function (result) {
var rt = result.d;
if (rt.Success) {
if (rt.Data) {
window.location.href = rt.Data;
} else {
ShowStatus("success", rt.Message);
}
} else ShowStatus("warning", rt.Message);
}
});
$('.loader').hide();
return false;
}
What causes redirecting is:
window.location.href = rt.Data;
Comment it or replace it with alert('success') or something else.
Try this:
$('#form').submit(function (e) {
e.preventDefault();
//your code
});

Categories

Resources