Grab Contents of jQuery POST call on C# Page - c#

New to the jquery ajax methods and I am just wondering how to capture the elements passed in the jquery.ajax() call using POST on a C# (ASP.Net) page.
Here is my jquery ajax call:
$.ajax({
type: "POST",
url: 'UpdateQuickLinks.aspx',
data: {"userid": contactid, "update": addString, "remove": removeString},
success: function(){
alert('Worked');
},
error: function(){
alert('Nope');
}
});
What do i put in the C# Codebehind on the UpdateQuickLinks.aspx page to capture
userid, update, and remove strings?

Your page's Request property has a Form collection of values submitted via POST:
var form = this.Request.Form;
var userid = form["userid"];
var update = form["update"];
var remove = form["remove"];

Related

Return view after ajax post to controller

I'm sending some json data with ajax by post
function SendF() {
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8",
success: function() {
},
error: function() {
alert("Oops! We've experienced a connection problem!");
}
});
}
to my controller
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
[...]
return View(flags);
}
and tried returning a view with data I've processed, but I guess it's not gonna happen since ajax is all about asynchronous http requests. How do I change my code to be synchronous?
The whole idea behind using ajax is to give the user the partial page update experience. If you are making an ajax call and once that is done and you are doing a redirect to another page, it does not give the partial page update experience to user. It looks very similar to the normal form submit(full page submit).
If you absolutely have to send the data to server via ajax , but want to do the redirect after the ajax call is successfully finished, you can do that using javascript in the success or done callback event on the $.ajax method.
All you have to do is, set the location.href property to the new url.
var flags = ["aa", "bb", "cc"];
$.ajax({
url: '#Url.Action("Summary")',
type: 'POST',
data: JSON.stringify(flags),
contentType: "application/json;charset=utf-8"
}).done(function(res) {
window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
console.log(error);
});
This assumes that your server action method returns a JSON response with the newUrl property which contains the url you want to redirect to .
[HttpPost]
public ActionResult Summary(List<string> flagsChecked)
{
return Json(new { newUrl = Url.Action("Index","Home") });
}
One way to do this would be to send the request to the controller via ajax and then render a partial view on your page. The easiest way would be to use the built in ajax helpers in ASP MVC. Here is a link to another post that gives a pretty good overview:
How to render partial view in MVC5 via ajax call to a controller and return HTML

Asp.net MVC Checkbox Event HTTPPOST ServerSide

net mvc5 form and Using checkbox.
My condition is i need to Call HTTPPOST action immedaitely after selecting the checkbox(true)
Its something like HTTPPOST action should be called immediately after selecting the checkbox.
I need to pass Model as well to the HTTP Post.
can you please let me know whats the desired way to get this done ?
I'd recommend using jquery to achieve this. Assuming your checkbox is nested in a form, you can use:
$(function () {
$('#CheckBoxName').change(function () {
$(this).closest("form")[0].submit();
});
});
This will trigger a postback, calling the appropriate HttpPost method and sending the model as a parameter.
You should use javascript to react on a change of the checkbox then posting via ajax.
Here is an exemple :
$('#checkbox').change(function(){
if (this.checked){
var jsonModel = '#Html.Raw(Json.Encode(Model))';
$.ajax({
type: 'post',
url: '#Url.Action("UrlOfPostAction")',
data: { Model: jsonModel},
dataType: 'json',
success: function (res) {
//Do something
}
//manage errors
});
}
});

Update List in ViewModel with Ajax ASP .NET MVC

I have a List (List) of Model objects which is presented in a view. I would like to add to that list without refreshing the page - therefore i thought Ajax is a great soloution. Im currently having a hard time getting it working.
My view is rendering a PartialView which contains the list.
Can somebody give me a hint how to pass a list to the controller and then back to the view without updating the whole page?
I hope my question makes sense.
/chris
EDIT:
I've been trying with JQuery. Looks like this:
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/Index", // Controller/View
data: { //Passing data
testString: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
}
}).success(function () {
$("#proever").load("/Video/Index");
});
})
})
With this method i get to HttpPost method in my controller. And i pass the parameters into it succesfully.
[HttpPost]
public ActionResult Index(CommentViewModel viewModel)
{
System.Diagnostics.Debug.WriteLine(viewModel.testString);
System.Diagnostics.Debug.WriteLine(viewModel.videoID);
System.Diagnostics.Debug.WriteLine(viewModel.taskID);
viewModel.testString = "new text string";
return View(viewModel);
}
The problem is now that i can't get the updated viewmodel back to the view.. What am i doing wrong?
In this example I don't update the list but just a test string to see if i can get it updated back to the view..
For those who's interested I solved the problem like this:
<script>
$(document).ready(function () {
$("#btnSave").click(function () {
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/AddComment", // Controller/View
data: { //Passing data
//Reading text box values using Jquery
sComment: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
}
}).success(function () {
console.log("good");
var txt = document.getElementById('txtArea').value;
console.log(txt);
var taskId = document.getElementById('dropVal').value;
var taskCont = $("#dropVal option:selected").text();
var taskContNum = Number(taskCont) - 1
console.log(taskCont);
var node = document.createTextNode(txt);
var para = document.createElement("div");
para.appendChild(node);
document.getElementById('taskPalace').appendChild(para);
document.getElementById('cola-' + '' + taskContNum).appendChild(para);
document.getElementById('txtArea').value = "";
});
})
})
So if the request succeeds without any errors in the HttpPost method it adds the comment to the database(through the HttpPost) and the jquery adds it to the view.
You need to use persistent data store in your case. Currently, your async post request will change the view model data but data is lost in subsequent http requests when you try to load the view with .load(...) jquery function.
1- Send async request to http post controller action to change the data in db store for example.
2- Read the view model data from db in http get index action. ($("#proever").load("/Video/Index"))
You can try this:
$(document).ready(function () {
$("#btnSave").click(function () {
var model = {
testString: $("#txtArea").val(),
videoID: '#(Model.Video.iVideo_ID)',
taskID: document.getElementById('dropVal').value
};
$.ajax(
{
type: "POST", //HTTP POST Method
url: "/Video/Index", // Controller/View
data: JSON.stringify({ viewModel: model })
async: false,
processData: false,
contentType: false,
dataType: 'json'
}).success(function (json) {
$("#proever").html(json.responseText);
});
})
})

How to call an Action method using ajax for a button click which is in partial view in MVC?

I'm new to MVC. I got a situation where I need to pass a parameter from view to controller on the button click (the button is in partial view), which then renders another partial view in the same page.
Steps followed:
I used jquery button click event for the button of partial view.
I made an ajax call to pass the parameters from my view to the controller.
The following is my code:
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$("#mainPageContainer").load("/Controller/Action", data, function(){
$.ajax({
//url: #Url.Action("Action", "Controller"),
type: GET,
data: {
id: data
},
success: function(){
}
error: function(){
}
})
}
})
Problem:
The problem is that, the data I'm received in the action method is null.
Please let me know if I'm missing anything.
Thanks in advance.
$(document).on("click", "#btninPartialView", function(e){
var data = $("txtinPartialView").val();
$.ajax({
url: "/Controller/Action",
type: GET,
data: {
id: data
},
success: function(result){
$("#mainPageContainer").html(result);
}
error: function(){
})
})
This should work.
Please check with the arguments your Action method is accepting.
for example if signature is
public ActionResult Action1(string name)
then you need to pass the data as
var data = { name : $("txtinPartialView").val() }
The problem is that you are mixing both jquery ajax and load function, load function sends an ajax call behind the scenes, so you need to use one of them, not both, so try like:
$(document).on("click", "#btninPartialView", function(e){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: GET,
data: {
id: $("txtinPartialView").val()
},
success: function(response){
$("#mainPageContainer").html(response);
},
error: function(){
}
});
});

How to call aspx page from javascript with query string

Currently the functionality of a web app I am designing(I can not tell real details) is as follows :
alert('Hi');
var args = ShowModalDialogue(sURL,'','');
if(args[0] == 'Pass')
alert('Bye');
Now I want to replace ShowModalDialogue with ModalPopupExtender. But the problem is I don't know how I can call aspx page using Javascript/Jquery and how to return values to calling javascript in the form of array?
Can anyone please help me out?
Thanks in advance.
You can use jquery to make an ajax call to your aspx.
var query = 'value1';
$.ajax({
type: "POST",
url: "my_asp_file.aspx?q="+query,
async: true,
dataType: "json",
data: data,
success: function(response) {
var js_object = JSON.parse(response);
},
error: function() {
}
});
Then you can use JSON.parse() to convert the returned JSON element to a JS Object. Remember to convert the output of your query in ASPX to a JSON object (in your ASPX file).

Categories

Resources