Making an Ajax call to a partial view after ajax success - c#

I have a partial view that contains all my buttons and it needs to display updated values after a form is submitted. At the submission I already have it rendering another partial view, is there a way to make it work where on success of that one being rendered it re-renders. Here is the code I am trying to get to work now based on what I've seen in other places.
jQuery in my view:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#ChangeGrade').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#HeatGradeDiv').find('input[name="grade"]').first().val();
var newname = $('#HeatGradeDiv').find('input[name="updatedGrade"]').first().val();
var heatname = $('#HeatGradeDiv').find('input[name="hiddenHeat"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
grade: origname,
updatedGrade: newname,
hiddenHeat: heatname
},
url: '#Url.Action("ChangeGrade","Home")',
success: function (result) { success(result); }
});
});
function success(result) {
$('#HeatGradeDiv').dialog('close');
$("#Partial_Chem_Analysis").html(result);
//ajax call I'm trying to get working
$.ajax({
type: "POST",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});
}
});
</script>
Here is the controller method I'm calling. When I run it now it is not getting hit.
public ActionResult ButtonsPartial()
{
ButtonsModel B = new ButtonsModel();
B.GetData(searchQ);
return PartialView(B);
}
Any help is appreciated.

If you attach it to a debugger such as (chrome developer tools or firebug) are you seeing any http or js errors?
It looks like you might need to make it a GET rather than POST...
$.ajax({
type: "GET",
url: "/Home/ButtonsPartial",
success: function (result2) { $("#ButtonsPartial").html(result2); }
});

Related

Why does my ajax call not returning my data from controller?

I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.

Access controller by JQuery

I have a view called InvoiceTo and a Controller called Order. Using JQuery, the default URL is: url: '', and this is the result:
locahost:port/domain/order/InvoiceTo
If I change the URL: url: /Order/GetInformation, this is the result:
locahost:port/domain/order/InvoiceTo/Order/GetInformation
I've already tried lots of way to set my url, but is always wrong. This is my JQuery:
$(document).ready(function () {
$('#InvoiceToDrop').change(function () {
var $div = $('#modalPartial');
var idcustomer = $(this).val();
$.ajax({
url: '/Order/GetInformation/' + idcustomer,
type: 'GET',
success: function (data) {
alert(JSON.stringify(data));
},
error: function (error) {
}
})
});
});
What I have to do to have this URL:
locahost:port/domain/Order/GetInformation/1
You can use the UrlHelper Url.Action method in the view:
$.ajax({
url: '#Url.Action("GetInformation", "Order", new { customerId })',
...
Or
url: '#Url.Action("GetInformation", "Order")/' + idcustomer
When the view loads #Url.Action is parsed and is replaced by the actual value.
Advantages of using this method are that it uses the routing table rather than statically typed urls.

return another MVC3 view of the same controller after ajax is used

How to return another view of the same controller? I made some debugging for the application: the ajax method calls the controller action, pass the parameter, executes the instructions. At the
return View("GetEmployeeDays", model);,
the "GetEmployeeDays" view receives the values from model and is populated, but finally in the browser I receive the initial view (from I made the request) - not the GetEmployeeDays view
routing code from Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
JQuery code that calls the action controller's and pass a parameter:
<script type="text/javascript">
$(document).ready(function () {
$('li').click(function () {
$.ajax({
url: '#Url.Action("GetEmployeeDays", "ApproveWork")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { userCode: $(this).attr('id') }
})
});
});
Controller action that should render the GetEmployeeDays view:
[HttpGet]
public ActionResult GetEmployeeDays(string userCode)
{
.....
return View("GetEmployeeDays", model);
}
If you want to simply load something to a part of your page without reloading to a new page, you should update the specific part of your page in the callback of your ajax function.
$(function(){
$('li').click(function () {
var uCode=$(this).attr("id");
$.get("#Url.Action("GetEmployeeDays","ApproveWork")?userCode="+uCode,
function(response){
$("#DivToBeUpdated").html(response);
});
});
});
If you want to redirect to a new view, you should do it by updating the location.href property value.
$(function(){
$('li').click(function () {
var uCode=$(this).attr("id");
var url="#Url.Action("GetEmployeeDays","ApproveWork")?userCode="+uCode;
window.location.href=url;
});
});
});
Without knowing what your original view is that is being re-rendered, I'd say that most likely your issue is that you should be returning this as a PartialView, since you are making an Ajax request. In addition, it doesn't look like you are actually rendering the result anywhere. What is your fiddler response? Does it show returned HTML? If it does, you probably just need to dump it onto the page by utilizing the .done callback within $.ajax.
<script type="text/javascript">
$(document).ready(function () {
$('li').click(function () {
$.ajax({
url: '#Url.Action("GetEmployeeDays", "ApproveWork")',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { userCode: $(this).attr('id') }
}).done(function() {
$(this).addClass("done");
});
});
</script>
You can't redirect via ajax request. Try a simple GET request:
<script type="text/javascript">
$('li').on('click', function()
{
document.location.href = '#Url.Action("GetEmployeeDays", "ApproveWork")' + '?param1=val1&param2=val2';
});
</script>
The controller is fine as it is now.
EDITED: Updated as requested
?Building from #David Diez, you can append parameters to your request as follows:
<script type="text/javascript">
$('li').on('click', function()
{
document.location.href = '#Url.Action("GetEmployeeDays", "ApproveWork", new { caseSensativeParamName = "foo" })';
});
</script>
You can, of course, go a JavaScript route as well. Something like this should work:
<script type="text/javascript">
$('li').on('click', function()
{
var targetUrl = '#Url.Action("GetEmployeeDays", "ApproveWork")';
var yourParam = $("#input-id").val();
targetUrl = targetUrl + '?yourServerParamName=' + yourParam;
document.location.href = targetUrl;
});
</script>
Cheers.

Calling action from jquery correctly?

I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});
Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});

Issue using JSON with JQuery and MVC

I'm trying to execute my controller from javascript using jquery... here is my jquery code that is executing..
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
var obj = msg.deserialize();
alert(msg);
}
});
});
</script>
Now it does execute my action..
Here is a sample of my controller class it is executing..
[AcceptVerbs(HttpVerbs.Post)]
[Url("Account/LogOn")]
public virtual ActionResult LogOn(string Username, string Password) {
if (Username == "test") {
return Json(new {
Success = true
});
} else {
return Json(new {
Success = false
});
}
}
Problem is.. when I run the method.. it just tries to download a "Logon" file which contains the result.. how do I put it back to an object in jquery so i can handle it the correct way, I've tried adding the success tag and attempt to check the msg but it doesnt even run it
Put your script inside document.ready before attempting to register any event handlers as the DOM might have not loaded yet:
<script type="text/javascript">
$(function() {
// ... copy - paste your script here
});
</script>
Also you don't need to set the dataType, jQuery knows it from the Content-Type response header from the server. Another remark: the msg object passed to the success handler is already a JSON object: you don't need to parse/deserialize it:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(msg) {
alert(msg.Success);
}
});
return false;
}
});
</script>
And the solution I would recommend you is to use the jquery.form plugin. Thanks to it your js code will look as easy as:
<script type="text/javascript">
$(function() {
$('form').ajaxForm(function(msg) {
alert(msg.Success);
});
});
</script>
Very neat stuff. You don't need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.
HIDDENHANCEMENT
var obj = msg.deserialize();
If that is not a joke, you would have spotted a hidden feature :)
If you're using jQuery v.1.4.x you don't need to parse a JSON string manually.
Using an older version, try
var obj = window.JSON.parse(msg);

Categories

Resources