Refreshing a page on button press - c#

newbie developer here and this is actually my first question on stack overflow. I'm in my first role as a developer and I've been given the task of finishing off an app that someone else started and I'm having a hard time getting the page to refresh when the users click a particular button.
The page has a list of items and each item has a checkbox next to it that users can put a check mark into and then click the Remove Items button. In theory clicking that button is supposed to refresh the page when it's done, or at least refresh the section of the page that contains the list..as far as I can tell. And the item is being removed, but the refresh isn't working so users are having to manually refresh the page before the items they chose to remove actually disappear off the screen.
Here's what's behind the button in controller:
[HttpPost]
public ActionResult UpdatePartStatus(List<tblPart> parts, tblArea area)
{
_LookupService.UpdatePartStatus(parts);
// return RedirectToAction("Details", area);
// return Redirect("~/Details");
return RedirectToAction("Parts", "Menu", false);
// <% return Response.Redirect(Request.RawUrl); %>
// return Response.Redirect(Request.RawUrl);
// return Page.Redirect(Page.Request.RawUrl, false);
// return Redirect(Request.UrlReferrer.ToString());
// return View();
// return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
}
The first line that's commented out is the way the previous developer left it. All the other lines that are commented out are the things I've tried so far, none of which worked. And the one that isn't commented out just happens to be the last one I tried before posting this. Most of those attempts are the results of searching around here on stack overflow
And here's the script from the Details view:
<script>
$('#btnAjax').click(function () {
....validation code I removed for this post....
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json'
})
}
});
</script>
And here's the MapRoute code that I've seen referenced in several other posts on this topic:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Parts", action = "Menu", id = UrlParameter.Optional }
The last thing the previous developer said before they left was that this is all standard MVC, nothing out of the ordinary but I'm running out of ideas.
I appreciate any thoughts or advice anyone can offer.
Thanks

The code you shared in question does not have anything to reload the current page. Looks like you are making an ajax form submit to the server. So it does not really make sense to return a redirect response from that.
If you want to reload the page, you can do that in the done event of the ajax call.
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(res){
window.location.href = window.location.href; // This will reload the page
}).fail(function(a, b, c) {
console.log('ajax call failed');
});
But again, If you are reloading the page what is the point of doing the ajax post ? Instead of realoding the page, you may simply remove the specific DOM element(s) you removed using javascript. This will give the user a partial page update experience without the entire page reload.
If you know the Id of the item you removed, you can use that in your jQuery selector to remove it.
var idOfDeletedItem = "someDomElementId";
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(res){
// Let's remove that DOM element from the DOM
$("#"+idOfDeletedItem).remove();
}).fail(function(a, b, c) {
console.log('ajax call failed');
});

Simply add a success function to the ajax request:
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json',
success: function() {
location.reload();
}
})

If you are using Ajax, then you should use
public JsonResult UpdatePartStatus(List<tblPart> parts, tblArea area)
{
_LookupService.UpdatePartStatus(parts);
return Json(null); //This will always return a null result to your ajax call indicating a success
}
For me, I usually do return json result this way :
try {
LookupService.UpdatePartStatus(parts);
return Json(new { Success = true});
}
catch {
return Json(new { Success = false});
}
And in your ajax call, do this:
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json',
success: function(result) {
if (result.Success)
location.reload();
} else {
alert("Delete failed");
}
}
})

Related

MVC Single String JSON post always coming Null in Controller

I am facing a strange problem in my MVC 5 application where I want to pass a Drop Down Selected value to controller using a Ajax post.
the Post code looks like this:
$(function () {
//Change the Value stream list each time the BU is selected
$('#Lob').change(function () {
alert(JSON.stringify($('#Lob option:selected').text()));
$.ajax({
url: '#Url.Content("~/Dashboard/GetValueStreams/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify($('#Lob option:selected').text()),
contentType: 'application/json',
success: function (VSList) {
// do stuff
});
}
});
});
});
The ALERT works fine and displays the selected value correctly. However in the controller, the string appears as null.
[HttpPost]
public ActionResult GetValueStreams(string BUName)
{
// Here the BUName parameter is coming as null.
}
I have tried changing my JSON POST data to the following:
data: {"BUName": JSON.stringify($('#Lob option:selected').text())},
This also does not work. Any help will be much appreciated. Thanks.
Change your data to data: JSON.stringify({BUName : $('#Lob option:selected').text()}).
I tested and it worked.
$.ajax({
url: '#Url.Content("~/Dashboard/GetValueStreams/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify({BUName : $('#Lob option:selected').text()}),
contentType: 'application/json',
success: function (VSList) {
// do stuff
}
});

MVC RedirectToAction Doesn't Work After JSON Post Return

I am trying to change the page after post process of the AJAX process which executes by MVC. I have used it different way maybe my usage might be wrong.
C# MVC code part. I am sending int list which is user list and process and do something.
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
My problem is redirect part do not work after the MVC process ends. Process works, only redirect doesn't.
JavaScript code here
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
Added this to AJAX and it is not working too
success: function() {
window.location.href = "#Url.Content("~/Courses/Index")";
}
Once you are using AJAX the browser is unaware of the response.
The AJAX success in its current form failed because redirect response code is not in the 2xx status but 3xx
You would need to check the actual response and perform the redirect manually based on the location sent in the redirect response.
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
Update
Working part for anyone who need asap:
Controller Part:
return RedirectToAction("Index","Courses");
Html part:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "#Url.Content("~/Courses/Index")";
}
});
Just deleted
dataType: 'json'
Part because I am using my own data type instead of JSON.

ajax post data is null in controller asp.net mvc 5

I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.
Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})
I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`

mvc razor does not redirect to url after action

I want to open Edit page of a product but after Index action it does not redirect to that page from list page. Here you can find my codes:
On my List page:
function getProductDetail(id) {
$.ajax({
type: "POST",
url: '#Url.Action("Index","ProductDetail")',
dataType: "html",
data: JSON.stringify({ "productId": id }),
contentType: "application/json",
success: function (result) {
}
});
}
</script>
And on my ProductDetailController:
public ActionResult Index(int productId)
{
Product prod = GetProductDetail(productId);
return View(prod);
}
As per the comments above, you don't need to use AJAX at all in this situation. If you were planning to dynamically update the DOM, using an asynchronous call to the server, this would make sense. In your case, since you are just redirecting to the page, it would make more sense to use an actionlink and get rid of the AJAX call completely.
#HTML.ActionLink("Link Text","Index","ProductDetail",new {productId = "1234"}, null))

Calling a c# methode from javascript/jquery and get the result

I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))

Categories