How to present partial view in jQuery dialog without navigating to another page - ajax

I have two controllers, A and B. A is responsible for representing some data in a grid view. Assume I have a button called "ShowInfo" which brings additional info about the selected record. And to retrieve the info about the selected record is the job of controller B.
The info is so little that it'd take just a tiny place in the corner if I navigate to another view. So I thought I'd rather bring that info inside a jQuery dialog without navigating to anywhere. But I'm a bit confused as to how to do it.
Here's the action method in controller B that is responsible for providing that info in a partial view.
public class BController:Controller{
public ActionResult GetInfo(int recordID){
RecordInfo info=RecordsRepository.GetRecordInfoById(recordID);
return PartialView(viewName:"RecordInfo",model:info);
}
}
I don't know, maybe the action method needs to different. Maybe I should return JSON instead of Partial view, but anyway, how do I do that?

You can use the jquery .get or .load methods. For example, to replace the contents of <div id="SomeElement"></div> with the partial view returned by GetInfo()
$('#ShowInfo').click(function() {
var url = '#Url.Action("GetInfo", "B")';
var ID = someValue; // the value to pass to the GetInfo method
$.get(url, { recordID: ID }, function(data) {
$('#someElement').html(data);
});
});

You can use Jquery ajax to achieve this.
Wrtire jquery ajax on the view page and call the partial view action from ajax.
receive the result in html format and replace it in the dialog box.
Put following code on main view page(ShowInfo button page)
$(document).ready(function(){
$("#ShowInfo").on("click",function(){ ///give id to showinfo button and attr data-id is record id
var id=$(this).attr("data-id");
$.ajax({
type: "POST",
url: "B/GetInfo",
data: JSON.stringify({ recordID: id }),
dataType: "html",
success: function (html)
{
////put the html response in dialog box
}
});
})
});

Related

Show Command Buttons Conditionally on hierarchy telerik grid

I want to show a custom command button in a telerik grid hierachy depending on the master-row data
Hi, I have a telerik hierarchy grid data, and I want to show a custom command button in the detail row, depending on the master-row data.
in the detail template grid, i call the ShowIfSubmitted() method.
command.Custom("Void").Text("Void").Click("VoidDeal").Visible("ShowIfSubmitted");
In the function:
function ShowIfSubmitted(dataItem) {
}
I only can access to the model data in the detail row.
But I want to access de master-row data, to check if the value of the property in the model meets the criteria to hide the button in the detail row.
My workaround was to extract the parent row instance model in order to get its id, with this field I created and ajax call to the DB to get all the info that I needed. Actually, with the "arguments" object, I could have extracted the id value.
Basically I just did this:
function ShowIfSubmitted(dataItem) {
var deal_status_id = 0;
$.ajax({
async: false,
data: { dealId: dataItem.Deal_Number },
url: '#Url.Action("action", "controller")',
success: function (data) {
deal_status_id = data;
}
})
return deal_status_id == submitted_status;
}
In the controller action is where I call the service.

Spring MVC Ajax updating DIV

Okay...I am coming from C# MVC using partial views/ajax, etc...
Here's what I have: 1 main page with a target ID that renders the default information using a page include.
What I want to do is onclick of a button target the original ID and render a different page as the include. Kind of like RenderPartials in C# MVC.
Can Spring (using Maven) MVC do this or is there a way to go about this that is strait forward?
Thanks,
You don't need to implement partial views just have an empty div and on click of a button make an ajax request get the content and update the div. something like below.
function button_onclick() {
var params = {}; //put parameter if any
$.ajax({
headers: {
Accept : "text/plain; charset=utf-8","Content-Type": "text/plain; charset=utf-8"},
url: "/controller",
method:"GET",
data:params,
success:function(data, textStatus,response) {
var text = response.responseText;
if (text == "") {
return;
}
$( "#DIV_ID" ).text(text);
},
error: function(response) {
alert(response);
// terminate the script
}
});
}

MVC Ajax Partial View Not Cached: Unique Element ID

I have a partial view which I load dynamically by calling a function similar to this as described here
$("#addItem").click(function() {
$.ajax({
url: this.href,
cache: false,
success: function(html) { $("#editorRows").append(html); }
});
return false;
});
As described, the cache is set to false to maintain the uniqueness of the elements. How does the code above acheive this? That is, what is the new ID that is assigned to the elements? How can I control these Ids?
I have a partial view where each I pass the id of a control to another control. However, I do not know how to do this after a partial view has been rendered dynamically. I need some way to figure out the new Id that is assign to each element.

mvc view insert into wrong "DOM" telerik window

Apologies in advance if this becomes a very long question...
Background Info
I have an MVC 3 application, using Telerik components and this particular issue is specific (I think) to the Window() component.
From my main view (Index.cshtml) I executing an ajax request to return a partial view which is what I am populating the contents of my window with. This is the jquery which is executing the request:
var url = '#Url.Action("GetAddPart", "Jobs")';
var window = $("#Window").data("tWindow");
var data = $("#indexForm").serialize();
window.ajaxRequest(url, data);
window.center().open();
the controller action is:
[HttpGet]
public ActionResult GetAddPart(MDTCompletedJobM model)
{
// show the AddPart window
//TryUpdateModel<MDTCompletedJobM>(model);
model.ActionTakenList = ActionTakenList;
model.ProblemTypes = ActualProblemList;
var addPartM = new MDTAddPartM() { CompletedJobM = model };
return PartialView(string.Concat(ViewDefaultUrl, "AddPart.cshtml"), addPartM);
}
this opens my window hunky dory.
in my partial view i have a form with two or three fields and an "Add", "Cancel button. For the sake of brevity I'll just show what I think are the relevant parts of the partial view, but i can produce the entire view if need be:
<div id="resultDiv">
#using (Html.BeginForm("AddPart", "Jobs", FormMethod.Post, new { id = "addPartForm", name = "addPartForm" }))
{
** layout components removed from here **
<input type="button" value="Add" class="t-button" id="btnAdd"/>
<input type="button" value="Cancel" class="t-button" id="btnCancel"/>
<p />
<div id="progressdiv">
</div>
}
</div>
is the "top level" tag in the partial view.
my jquery to handle the Cancel button is:
$("#btnCancel").click(function () {
var window = $("#Window").data("tWindow");
window.close();
});
In my main view, I have a submit button, which when completed effectively reders the main view "disabled" or displays errors. The action for this submit button returns the main view:
Controller's action snippet:
if (ViewData["DoPayJobWarningStr"] == null)
return RedirectToAction("GetAutoDispatchJob", new { autoDispatchJob = model.JobReferenceNumber});
else
return View(string.Concat(ViewDefaultUrl, "Index.cshtml"), tmpModel);
My actual problem
For a specific example I am using, I am expecting ViewData["DoPayJobWarningStr"] NOT to be null, there the return View(...) will be executed.
if I execute this action (for the submit button) without opening the window, my view returns correctly and the page is updated to show the warning message. However, if I open the window first then execute the submit button, the View isn't updated on the page, but seems to be placed into the Window's html. ie, if I hit the submit button (nothing happens), then click on the button which opens the Telerik window, I briefly see the View returned by the submit Action being shown before it's updated with what the Partial View should contain. I don't understand at all how or why the returned View is being placed there?
Things I've tried:
Commenting out the ajax request (window.ajaxRequest(url, data);) fixes the issue (even though I obviously have a blank partial view to look at).
Not making the Partial View a "Form" doesnt' work
No matter how I "close" the window, the view is still placed within there. eg clicking the x in the top right hand corner
Using Firebug, the HTML after the submit button is clicked is not updated.
Rather than using "window.ajaxRequest(url, data)", i've also tried (with the same result):
$.ajax({
type: "GET",
cache: false,
url: url,
data: $("#indexForm").serialize(),
success: function (data) {
var window = $("#Window").data("tWindow");
window.content(data);
window.center().open();
$("#progress").html('')
},
error: function (e) {
alert(e.Message);
}
});
Is it all possible to determine what I am doing wrong? Is it the ajax request? Only assuming that because removing it fixes the issue, but there might be more to it than that.
Thanks and of course if you need more info, ask :)
Thanks
EDIT
After suggestions from 3nigma, this is what I've updated to (still no luck)...
Telerik window definition:
#{Html.Telerik().Window()
.Name("Window")
.Title("Add Part")
.Draggable(true)
.Modal(true)
.Width(400)
.Visible(false)
.Height(270)
.ClientEvents(e => e.OnOpen("onWindowOpen"))
.Render();
}
jquery function which is an OnClick event for a button:
function AddBtnClicked() {
$("#Window").data('tWindow').center().open();
}
the onWindowOpen event:
function onWindowOpen(e) {
//e.preventDefault();
var data = #Html.Raw(Json.Encode(Model));
var d2 = $.toJSON(data);
$.ajax({
type: 'GET',
url: '#Url.Action("GetAddPart", "Jobs")',
data: d2,
contentType: 'application/json',
success: function (data) {
var window = $("#Window").data("tWindow");
window.content(data);
$("#progress").html('');
},
error: function (xhtr, e, e2) {
alert(e +'\n' + xhtr.responseText);
}
});
};
OK.
Issue was related to this line in the Partial View:
<script src="#Url.Content("~/Scripts/ValidationJScript.js")" type="text/javascript"></script>
As soon as I took that out, it all works. Not sure why that was causing the issue - I don't think it had been previously been loaded but maybe it had which was causing the problem.
Thanks to 3nigma for your thoughts, nonetheless!

Auto Complete for Generic list MVC 3

I have a Generic list in my Model class. I want to have a textbox with autocomplete in my view which fills data from the generic list. How can I do this?.
For this you will need
Function on server side which will return list of matching data and will accept string entered by the user.
Something like this
public JsonResult AutoComplete(string input)
{
//Your code goes here
}
In the View, for the text box you need to bind KeyDown event. You can take help of jQuery for this. On key down handler you will make an Ajax call to the function you have defined in the Controller. Some thing like this:
$.ajax({
url: '#Url.Action("AutoComplete", "ControllerName")',
data: 'input=' + sampleInput,
success: function (data) {
//Show the UL drop down
},
error: function (data) {
// Show Error
}
});
In response you will get list of strings, which you will need to bind to some html element like "UI". Once done, display this UI with proper CSS below the text box. Using jQuery, you can retrieve the pixel location of text box too.
You can not use Asp.Net Auto Complete box in your project as you are developing app in MVC (no viewstate). I hope you get the idea.
You can use JQuery Autocomplate.
To fill the list, you can populate the data from you object.
I can't remember the exact Razor syntax, but you can refer to this:
//data is your Model object of type List<String>
var listString = [#foreach(x in data) { '#x',}];
$( "#dataList" ).autocomplete({
source: listString
});
<input id="dataList">
JQuery Autocomplte
http://jqueryui.com/demos/autocomplete/
This is client side auto complete, I can provide server side if you need.

Resources