Get data from the server and display in the Edit Form - javascript

This question is continuation of the following question Add JSON data to the view that unfortunately ended up unresolved yet.
In my main view which has a form with 2 controls and placeholder for flexigrid I added the following at the bottom
<div id="add-edit-dialog" style="display: none" title="Add / Edit Client">
#Html.Partial("_ClientForm", Model)
</div>
The flexigrid pluglin instantiates in run-time and adds 3 buttons: Add, Edit, Delete.
For Edit button I need to get the current row information from the server and then display it in the Form. For Add button I do not need to go to the server (I think).
This is my current code for the Edit button:
function edit(com, grid) {
$('.trSelected', grid).each(function () {
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row') + 3);
currentId = id;
$('#fntype').val('Edit');
var ClientName;
ClientName =$('.trSelected td:eq(2)').text();
var url = '/Client/Edit/' + id ;
$.getJSON(url, function (html) {
// setFormControls(data.Id, data.Role, data.Location, data.JobType,
// data.Description);
// alert(data);
$($dlg).html(html);
});
//location.replace(url);
RunModalDialog("Edit Client: " + ClientName);
});
So, it is going to Edit controller action and returns that same partial view _ClientForm with correct information passed as a model. If I look at the response result returned in FireBug I can see that the returned HTML is correct and all the textboxes have correct information in their values.
However, the dialog that opens looks exactly the same as the dialog for the Add button - in other words, all form controls come blank. I can not figure out what is wrong and why it is not working the way I want it.
This is what I have for the RunModalDialog:
var validator = $("#add-edit-form").validate();
var $dlg = $("#add-edit-dialog").dialog({
autoOpen: false,
show: "blind",
closeOnEscape: true,
resizable: true,
width: 1200,
height: 750,
minHeight: 600,
minWidth: 950,
buttons: {
"Save": function () {
if ($("#add-edit-form").valid()) {
// jobPost.setVals(txtId.val(), txtRole.val(),
// txtLocation.val(), txtJobType.val(),
// txtDescription.val());
$.ajax({
type: 'POST',
//data: JSON.stringify(clientInformation),
url: '/Client/Save',
dataType: 'json',
contentType: 'application/json',
success: function (result) {
// insert new list into grid
$('#flexClients').flexAddData(result);
}
});
$(this).dialog('close');
} else return false;
},
Cancel: function () {
$(this).dialog("close");
clearForm();
if (validator)
validator.resetForm();
}
},
close: function () {
clearForm();
},
open: function () {
//$("#add-edit-dialog").parent().appendTo($("#add-edit-form"));
}
});
function RunModalDialog(title, url) {
if (title) {
$dlg.dialog("option", {"title": title });
}
if (url) {
$dlg.load(url).dialog("option", { "title": title }).dialog("open");
//$dlg.load(url, function () {
// var validator = $("#sform").validate();
// if (validator)
// validator.resetForm();
// $dlg.dialog("option", { "title": title }).dialog("open");
//});
} else {
$dlg.dialog("open");
}
}
The code with the load (and commented code) was another attempt to solve this problem. That sort of worked (the form displayed with the info), but the main Client view was also reloaded so I was seeing double grid.
Do you see what should I change in my code to get this thing working?
Thanks a lot in advance.

With Jazzen Chen from MS help we solved this problem. All I needed to do to display the data correctly was to change getJSON to just get jquery function. Now my form comes with data populated correctly and the next challenge will be to save the data.

I posted a blog post with what I have so far - hope it may help
http://blogs.lessthandot.com/index.php/WebDev/UIDevelopment/AJAX/asp-net-mvc-project-with

Related

jquery dialogue destroy syntax

I have a dialog box that loads a partial view, called from a number of different views in my MVC 4 app. It has a text area and a small notice of how many characters are remaining in the text area. All works fine on page load, however when the dialog box is closed, whether by the send button or the close button in the dialog titlebar, when it is reopened the '#textarea_feedback' div content disappears until a page reload. I believe I should be using dialog('destroy') but cannot seem to get the syntax right. Either it has no effect or it displays the partialview at the bottom of the page. Please advise, hope I've included enough code to identify the issue. Thanx
$(document).ready(function () {
var text_max = 160;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#txtMessage').keyup(function () {
var text_length = $('#txtMessage').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
$('#send').click(function (e) {
if ($('#txtSMSMessage').val().trim()) {
e.preventDefault();
$.ajax({
type: "POST",
data: $('form#Composer').serialize(),
url: '/MyController/MyAction',
success: function (data) {
alert('Sent');
$('#Composer').closest("div.ui-dialog-content").dialog("close");
},
error: function (a, b, c) {
$("#Composer").unblock();
alert(b);
}
});
//$('#Composer').closest("div.ui-dialog-content").dialog("destroy");
}
});
//var dialog = $('#Composer').closest("div.ui-dialog-content").dialog();
//console.debug(dialog);
//dialog.on("dialogbeforeclose", function (event, ui) {
// dialog.dialog('destroy')
//});
});
Wanted to post answer in case it could help someone else, really was LShetty's comment that lead me in the right direction. Added to the CLOSE function of the Ajax call that created the dialog box:
$.ajax({
url:
...
type: "POST",
success: function (responseText, textStatus, XMLHttpRequest) {
dialog.html(responseText);
dialog.dialog({
...
title: 'Send message',
open: function () {
...
},
close: function () {
$(this).dialog('destroy').remove()
},
...
});
}

$.when(ajaxCall) Versus success

I have the following code inside my asp.net MVC view:-
$('body').on("click", "#transferserver,#transfersd,#transferfirewall,#transferrouter,#transferswitch", function () {
$("#showoptions").dialog({
title: "Assign Selected Records To New Rack",
width: 'auto', // overcomes width:'auto' and maxWidth bug
maxWidth: 600,
height: 'auto',
modal: true,
fluid: true, //new option
resizable: false
});
var ajaxCall = $.ajax({
url: '#Url.Content("~/Rack/ShowTransferSelectedDialog")',
data: {
rackfrom: "#Model.Rack.ITsysRackID",
assettype: $(this).attr('id')//get the id for the clciked link, so that the submit button will call the associted action method.
},
type: 'get',
success: function (html) {
$('#showoptions').html(html);
$("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
}
});
$.when(ajaxCall)
.then(function (data) { showDialog(data); });
});
I have the following questions:
What are the differences between the $when(ajaxcall) and on success ?
In my above code if I remove the $.when(ajaxCall) the dialog box will still be displayed . so is there any need to have it?
Thanks
EDIT
But one benefit i find for using $.when(ajaxCall) is that i have defined a custom authorization attribute as follow:-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var viewResult = new JsonResult();
viewResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
viewResult.Data = (new { IsSuccess = "Unauthorized", description = "Sorry, you do not have the required permission to perform this action." });
filterContext.Result = viewResult;
}
}
}
currently if the user clicks on the link to display the dialog box and he is not authorize to do so , he will receive a jAlert containing the unauthorized message as follow:-
![enter image description here][1]
but if i remove the $.when(ajaxCall), then the user will not receive the unauthorization message , and instead the dialog will be blank .. so can anyone advice ?
1) This is the definition of jQuery when
Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
It make no sense to use it for a single ajax call, you want to use it for 2 or more so you wait for them to finish before executing some code.
2) I don't know what showDialog does but your dialog already shows because in your success handler you have $("#showoptions").dialog("show");. Again, no need at all to use when here

MVC4, Render Partial View in Dialog Box with jQuery, How to refresh

I have a partial view that is popping up in a dialog with the code below. However, after the user saves the partial view the data does not refresh in that partial view when I click the ActionLink again until I stop debugging and restart the app. However, the new record is in my databsae. The other issue is when I restart the app I cannot update the record because of the error below. What am I missing? Thanks.
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
The div tag in my View
<div id="assign-dialog"></div>
The ActionLink in the same view
#Html.ActionLink("Assign", "Edit", "Assignment", new { id = Model.InfoId}, new { #class = "assign-modal" })
The jQuery
$(function () {
$(function () {
$('#assign-dialog').dialog({
autoOpen: false,
width: 400,
height: 500,
resizable: true,
modal: true
});
$('.assign-modal').click(function () {
$('#assign-dialog').load(this.href, function () {
$(this).dialog('open');
});
return false;
});
});
The HTTP GET action
[HttpGet]
[Authorize(Roles="Admin")]
public ActionResult ViewAssignment(int id = 0)
{
RequestAssignment query = _assignmentRepository.GetCurrentAssignment(id);
return PartialView("_ViewAssignment", query)
}
UPDATE:
I originally followed the steps in javascript/jquery modal popup dialog MVC 4 / render partial view under the dynamic section of Jasen's answer, but did not know what to put in the "Client Partial, empty for now "
...okay so going off some other posts I have read this is what I was able to come up with, but nothing happens when I click my link.
View html
Assign
<div id="assign-modal">
</div>
jQuery
//Dialog Box for Assignments
$(".dialog-trigger").on("click", function(event) {
event.preventDefault();
var infoId= $(this).data("infoId");
$.ajax({
url: "RequestAssignment/Edit/" + infoId,
type: "GET"
})
.done(function(result) {
$("#assign-modal").html(result).dialog("open");
});
});
so after some long searching, I decided to use Ajax.ActionLink. I know there are better ways out there, but this one was working for me. I want to thank #MattBodily for all the help along the way.
#Ajax.ActionLink("Approve", "QuickAssign", "Assignment", new { id = Model.InfoId}, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "result", InsertionMode = InsertionMode.Replace, OnSuccess = "openDialog" })
then my javascript function
function openDialog() {
//set the diaglog properties
$("#result").dialog({
title: 'Assign',
width: 550,
height: 'auto',
modal: true
});
$("#result").dialog("open");
}

How do I set doubleClick function to call custom function in jqGrid

I have added a custom edit button control on the jqGrid navigator as follows:
jQuery("#grid").navButtonAdd('#pager',
{
caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editSelectedRow,
position: "last",
title:"click to edit selected row",
cursor: "pointer",
id: "edit-row"
}
);
So that rather than use the default function: editGridRow, it uses my custom function editSelectedRow. However, I also want to add the doubleClick function to so that it calls editSelectedRow on doubleClick.
using the default editGridRow function works as such
ondblClickRow: function()
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
jQuery(this).jqGrid('editGridRow', rowid);
}
However, when I replace the default editGridRow function with my default function editSelectedRow as such,
ondblClickRow: function()
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
jQuery(this).jqGrid('editSelectedRow', rowid);
}
I get the following error within firebug:
uncaught exception: jqGrid - No such method: editSelectedRow
The function editSelectedRow however does exist and works with clicking the custom edit button. Please help, thanks.
UPDATE:
#Oleg: As requested here's the code defining method: editSelectedRow
function editSelectedRow(rowid)
{
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
if( rowid != null )
{
var dialogId = '#edit-form-dialog';
var dialogTitle = 'Edit Customer';
$(dialogId).load('/customer/edit/id/' + rowid, function ()
{
$(this).dialog(
{
modal: false,
resizable: true,
minWidth: 650,
minHeight: 300,
height: $(window).height() * 0.95,
title: dialogTitle,
buttons:
{
"Save": function ()
{
var form = $('form', this);
$(form).submit();
$("#grid").trigger("reloadGrid");
},
"Cancel": function ()
{
$("#grid").trigger("reloadGrid");
$(this).dialog('close');
}
}
});
LaunchEditForm(this);
});
}
else
{
jQuery( "#dialogSelectRow" ).dialog();
}
return false;
}
#Oleg: Thanks, you advised against using a custom method editSelectedRow in place of method editGridRow. The reason I am using this is that my forms are Zend Forms and I need all the bells and whistles of Zend Form to be available. The server generates this form and it's loaded into a dialog form. If there's a way to still achieve this without resorting to my editSelectedRow custom method, I'd be glad to learn it. Thanks.
You question is pure JavaScript question.
If you define the function editSelectedRow as
function editSelectedRow(rowid)
{
...
}
you can call it as editSelectedRow(rowid) and not as jQuery(this).jqGrid('editSelectedRow', rowid);.
Another problem is that you use this inside of he body of editSelectedRow function. It's not correct. You can define editSelectedRow function in a little another way
var editSelectedRow = function (rowid) {
...
};
In the case editSelectedRow will be able to bind this to any value. To do this you need use another form of invocation of the function. Inside of ondblClickRow it will be
ondblClickRow: function () {
var rowid = jQuery("#grid").jqGrid('getGridParam','selrow');
editSelectedRow.call(this, rowid);
}
In the above example the first parameter of call is the value used as this inside of the function. We forward just the current this value forward to editSelectedRow. If we would use the form editSelectedRow(rowid); for the invocation of the function the value of this inside of function will be initialized to window object.
The usage of editSelectedRow inside of navButtonAdd can stay unchanged.

jQuery dialog: how to prevent closing the dialog + an extra get request!

The work flow:
user click the button, a dialog box opens with a search form. An ajax post request is sent to the server, and get a json response. I get the callback on success handler. Now two issues.
the dialog closes upon success callback (successFn). I get the json response in the success call back, and I want the user to see the result and press close button to terminate the dialog,.
Soon after the dialog closes, a get request is sent to server. After closing the dialog by itself, the url is like http://localhost:8080/search?query= . I do not send any GET request explicitly
jQuery(document).ready( function(){
jQuery("#myButton").click( showDialog );
$myWindow = jQuery('#myDiv');
$myWindow.dialog({ width: 400, autoOpen:false, title:'Hello World',
overlay: { opacity: 0.5, background: 'black'},
modal: true,
/*open: function (type, data) {
// include modal into form
$(this).parent().appendTo($("form:first"));
}, */
buttons: {
"Submit Form": function() { $('form#myform').submit();},
"Cancel": function() {$(this).dialog("close");}
}
});
});
var showDialog = function() {
$myWindow.show();
$myWindow.dialog("open");
}
var closeDialog = function() {
$myWindow.dialog("close");
}
var successFn = function (response) {
var obj = JSON.parse(response);
$("#result").html('').html(obj.name);
}
var errorFn = function (xhr, ajaxOptions, thrownError){
$("#myform").parent().html('').html(xhr.statusText);
}
var query = $("input#query").val();
var dataString = 'query='+ query ;
$('form#myform').submit(function(){
$.ajax({
type: 'post',
dataType: 'json',
url: '/search',
async: false,
data: $("#myform").serialize(),
success: successFn,
error: errorFn
});
});
It would be a good idea to add method="post" to your form to avoid any accidental GET data being sent.
Adding return false; to the success function may stop the dialog from closing. I'll test this if I can.
Edit: also check that all your code is inside jQuery(document).ready( function(){
Hope that helps!
I think you just need to add return false.
"Submit Form": function() { $('form#myform').submit(); return false;},

Categories