Sending Data from View to Different Controller without QueryString - c#

I need to pass data from View to Controller(From TestView1 to TestController2)
#Html.ActionLink("Text", "Index", "Sample", new { testId = test }, null)
Currently this is sending Data in QueryString. But i need to avoid this and pass data to Controller without Query string ?
How do i achieve without Querystring ?
I searched and most of them were by using Query string. If i missed out on solutions please redirect to correct path.
Thanks

Have you tried to post your data to the controller, if possible? Keeping a form and hidden fields..
e.g http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx

You can send data using Ajax call back. try this method on your link/button
#* Your button/link *#
<input type="button" onclick='Link1()'" value="Submit" />
<script type="text/javascript">
function Link1() {
var Id = $("#txt").val();
$.ajax({
url: '#Url.Content("~/Test2/Actionname")',
type: 'post',
async: true,
data: { text: Id },
success: function (data) {
alert("Success");//Ajax request success
alert(data);//data from Test/yourAction
},
error: function (err) {
alert("fail");//Ajax request fail
alert(err.responseText);//error will displayed here
}
});
}
</script>

Related

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(){
}
});
});

Accessing request from external url

Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.

Pass Model from View To Controller Using ActionLink

what is the best way to pass model data from View to Controller using actionLink. actually my action link is download link and i want to pass report model as it contains datatable information.
private void DownloadReport(ReportModel rptModel)
{
// want to recieve report model here.
// to do so.
}
An ActionLink is ultimately just an anchor element.
Instead, use a form with an anchor element that submits the form.
The corresponding controller method would accept your ReportModel.
You can use Ajax post method for the same..
For example in your view :-
<script type="text/javascript">
var rptModel = {
val1: "val1",
....
};
$.ajax({
url: '/NameOfController/DownloadReport,
type: 'POST',
data: JSON.stringify(rptModel),
contentType: 'application/json; charset=utf-8',
success: function (data.success) {
alert(data);
},
error: function () {
alert("error");
}
});
</script>
And this whatever you pass from view you will get in your action method.

ASP.NET MVC post controller get json, generate file and return it

I have an ajax post request:
function downloadElevationMap() {
var jsonData = ko.toJSON(mod.SelectedItem);
$.ajax({
url: '/Home/GetData/',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: jsonData,
success: function (data) {
console.log("OK");
},
});
}
The controller method recive data correct. The code is presented below:
public FileStreamResult GetData(Mv jsonData)
{
var resultAll = jsonData.Data.Select(d => d.y).ToList();
var str = new StringBuilder();
_fileName = "ses"+jsonData.Path;
foreach (var d in resultAll)
{
str.Append(d + " ");
}
var byteArray = Encoding.ASCII.GetBytes(str.ToString());
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", string.Format("{0}.txt", _fileName));
}
Mv - is my class that represent data. When debug the both str and stream variable contain correct data.
Function downloadElevationMap() is called by onclick="downloadElevationMap()"
I just want when downloadElevationMap() is called the GetData controller return a file for download. But simply nothing happend. Where the error is?
well you dont need ajax to do that try this
window.location="download.action?para1=value1...."
for your needs you can do some thing like this
window.location="/Home/GetData/?"+$.param(jsonData )
I'm fairly sure what you are doing is swallowing the data in the success callback in the AJAX call - all your code will do is download the file, call the success callback, and then just print "OK" to the console.
As Anto said, you don't need AJAX (and, indeed, should not be using AJAX) for this. His answer is absolutely correct, provided you can use a GET string. If you need to use a POST request, create a form with hidden inputs and submit that - something like:
HTML
<form action="/Home/GetData" method="POST" id="dataToSubmit">
<input type="hidden" name="param1" value="value1" />
<input type="hidden" name="param2" value="value2" />
<input type="hidden" name="param3.param4" value="value3" />
</form>
JS
function downloadElevationMap() {
// Write code to map your jsonData to your form elements
$('#dataToSubmit').submit();
}
You could make the form dynamically if you wish. You might be able to update your page to post directly with a submit button.
One final note, you don't need to submit the data as Json. If you have
{
"param1": "value1",
"param2": "value2",
"param3": {
"param4": "value3"
}
}
then if you just use the format in the form above, it will submit fine - this reference explains how to submit to deep models.

how to send JavaScript string from view to controller?

I'm doing a project in visual studio mvc4 c# trying to send a string from a JavaScript function in a View to a controller. I tried to use the Session Object like this:
in the View:
Session["matStr"] = matrixString;
in the Controller:
var s = (string)Session["matStr"];
but when I get to the controller the Session returns me null.
so I'll be glad to know the answer how to send a JS' string from view to controller thank in advance..
You can use the following code to call a controller Action
$('#btnSendData').click(function() {
//Send batch to the server
$.ajax({
type: 'POST',
url: '#Url.Action("SessionUpdate")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(sessionvalue),
success: function(result) {
alert(result);
}
});
return false;
});
Here SessionUpdate is a conroller action and you can set the session value as sent in sessionvalue variable and can get the result.
use input hidden field
<input type="hidden" id="hid1" runat="server"/>
$("#hid1").val("the val from client to server");
then get the value in server side.
i hope that thats what you need.(use the string in server side).
you can also just use some span to set the string in controller
You need to include a name for the input. This is what MVC uses to communicate with the View and controller for POSTS.
<input type="hidden" id="hid1" name="hid1"/>
$("#hid1").val("string");
Then on your controller action you use it as a parameter.
public ActionResult Index(string hid1)
{
return View()
}

Categories

Resources