Window.location.href post parameters to actionresult asp.net mvc - javascript

I try to post textbox value to actionresult in asp.net mvc
Javascript:
function OnButtonClick() {
var data= {
TextBox: TextBox.GetValue()
};
var PostData= data.TextBox;
window.location.href = "Home/MyActionResult?Page=data" + PostData;
}
ActionResult
public ActionResult MyActionResult(string PostData)
{
return view();
}
Whenever I post data to Home/MyACtionResult , PostData is always null,
What am I missing ?
How can I post textbox value to actionresult?

Try with this:
window.location.href = "Home/MyActionResult?Page=data&PostData=" + PostData;

Try this
var url = '#Url.Action("../Home/MyActionResult")' + '?Page='+data+'&'+PostData;
window.location.href = url;

This type of passing data is a bad approach. Please try to look into another code approach. This will not work for huge data, urls, secured data.

With window.location.href you can't use POST method.
But here is simple trick if you don't want to you GET method.
You can use cookies and then
function OnButtonClick() {
setCookie("param1",value1,30);
setCookie("param2",value2,30); // and so on, fetch input names and values using javascript
window.location.href = "Home/MyActionResult"
}
And then you can get cookies values from your MyActionResult page and use it.
Ofcource you have to include setCookie function as well in your page.

Related

Controller doesn't receive one parameter from url query

ASP.NET, I have a controller with this GET method:
public ActionResult Index(String state, String searchNumber, String searchCustomer, int? page)
{
}
in the view I call it in this way:
$("#btnSearch").click(function (event) {
var params = {
state: '#ViewBag.State',
searchNumber: $('input[name=searchNumber]').val(),
searchCustomer: $('input[name=searchCustomer]').val()
};
var url = window.location.href + "/Index/?" + jQuery.param(params);
window.location.href = url;
});
where the #ViewBag.State is a String received from the controller while the other fields are from texboxes.
Here a real example of the url value:
"http://localhost:49396/Orders/Index/?state=Opened&searchNumber=17&searchCustomer="
In the controller Index function the searchNumber variable is set to "17" but state to null.
Why the first one is not recognized?
#ViewBag.State is Razor syntax. Razor is working in your cshtml files, but javascript files are not parsed/processed.
One way to get the property anyway is to add an hidden field to your view with the value set to #ViewBag.State. Then read the value from the hidden field in javascript - just like you are already doing it for the other two properties.

asp.net Javascript window.location Url.Action not working

I try to get a JavaScript working within ASP.NET
My JavaScript:
function reportOrder(sender, args) {
alert("Message");
window.location.href = #Url.Action("StartReport", "PrintOut", New With {.Area = "Printing", Key .ReportName = "Test",
Key .typeOfReport = TypeOfPrintingIS.Order,
Key .CompanyId = DirectCast(ViewData("CompanyId"), Guid),
Key .ExchangePrintData = CType(locOrderReport, ExchangeData.IExchangePrintData)});
}
First of all, the function works, when I disable the window.location, the alert is raised! So, the Problem has to be within the #UrlAction(
And also, the Area is working, because, when I use a similar Html.RenderAction function with an other directive to another function, it works fine.
The function within the Controller:
<HttpPost>
Function StartReport(ReportName As String, typeOfReport As TypeOfPrintingIS, CompanyId As Guid, ExchangePrintData As Code.ExchangeData.IExchangePrintData) As ActionResult
Dim model As New HTML5ViewerModel()
model.ViewerOptions.UseUIMiniStyle = True
locReportHelper.CompanyId = CompanyId
locReportHelper.ReportName = ReportName
locReportHelper.TypeOfReport = typeOfReport
locReportHelper.ExchangePrintData = ExchangePrintData
model.ReportName = locReportHelper.CreateReportId
Return View("Html5Viewer", model)
End Function
And the "IExchangePrintData" Interface is an empty Interface to verify the correct class.
Does anyone of you got an idea?
THX a lot - Have a nice weekend
Try to wrap your razor directive with single quotation marks. It looks like this one: window.location.href = '#Url.Action("SomeActionName", "SomeControllerName", etc...)';
Guess this should work, cause of you mentioned #Html.RenderAction worked fine.

Pasing Javascript result to View

I got a Question, I'm really new in working with Asp.net.
I got a Javascript where I woult like to pass Data to my Controller.
<script type="text/javascript">
$("#SearchButton").on("click", function () {
var $sucheMoped = [];
$("#tab_logic tbody tr")
.each(function () {
var $Item = $(this);
var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
alert(suchfeld + "&&&" + schluessel);
$sucheMoped.push({
Suchfeld: suchfeld,
Suchschluesseltyp: schluessel
});
});
window.open('#Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
})
</script>
I just would like to pass the "sucheMoped" from my javaScript to my Controller.
My Controller is just expecting a IEnumarable of Objects with Properties Suchfeld and Suchschluesseltyp.
Anyone an idea?
Thanks Guys.
First of all, you need to change the way you invoke the controller action. You should stringify the array using the JSON.stringify() method.
So, this should look like this:
window.open('#Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));
Then, you need to create a custom model binder to bind your array with the action parameter. This is a simple array model binder for demonstration purposes only, it doesn't take into account failures or whatever, but it works in this scenario, passing the correct data, so please modify it to fit your needs.
public class ArrayModelBinder: DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);
return array;
}
}
What I do here, is to get the query string submitted through the URL, convert it with JsonConvert.Deserialize<T> method and return it.
You simply need to decorate your parameter in the controller's action with the custom model binder, like this:
[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
return View(SuchObject);
}
Edit
window.open is useful if you want to open a new browser window. You could use it to open a new tab as well.
In order to navigate to another location without opening a new tab or window, use the window.location property like the following:
window.location = '#Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);
If you use the jQuery.ajax method, you can pass complex objects as data parameter.
$.ajax({
url: '#Url.Action("MainView", "MainView")',
type: 'GET',
data: { 'SuchObject': $sucheMoped },
success: function (htmlContent) {
// write content to new window (from http://stackoverflow.com/a/23379892/1450855)
var w = window.open('about:blank', 'windowname');
w.document.write(htmlContent);
w.document.close();
}
});
You can use jquery library $.getScript to call the action method in your controller and the return javascriptResult type in your action.
$.getScript("Home","Display")
// Home Controller
private JavaScriptResult Display()
{
string message = "alert('Hello World');";
return new JavaScriptResult { Script = message };
}

How do I make AJAX grab the data from the controller in MVC?

So, I have this AJAX call and what I want to do is for the controller to return the string as a JSON object back to the view where my ajax call is. Now here's the thing. I don't know how to do it and which class would help me do it. Everything I've tried doesn't work at all. My question is when I use the $.post method how do I make AJAX "grab" the data back from the controller?
Since people comment on my Javascript, I don't mind that, I'll fix it later. The question is
How do I return anything I want from the controller in MVC? The controller is where I need help
Here's my call:
<script>
$(document).ready(function () {
alert("document ready");
// Attach a submit handler to the form
$("#searchForm").submit(function (event) {
alert("submitsearchForm");
//event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
query2 = $form.find("input[id='query']").val(),
url = "/umbraco/Surface/SearchDictionarySurface/HandleDictionarySearching/";
alert("query2" + query2);
// Send the data using post
var posting = $.post(url, { query: query2 });
alert(url);
//Put the results in a div
posting.done(function (query2) {
var content = //bla bla bla;
$("#result").empty().append(content);
alert(query2);
});
});
});
</script>
Also, I'm using Umbraco. That's why the surface controller:
using MyUmbraco.Models;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
namespace MyUmbraco.Controllers
{
public class SearchDictionarySurfaceController : SurfaceController
{
// GET: SearchDictionarySurface
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult HandleDictionarySearching(string query)
{
if (!string.IsNullOrEmpty(query))
{
var query2 = Json.parse(query);
//return Json object????
//I NEED HELP HERE
}
else
{
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
}
}
}
}
So, to any newbies out there that might need the help I needed (and because I've been looking for this thing for AGES and nobody responds, here's how you do it:
Your JQuery callback function, and your controller must have the same variable. E.g:
Controller:
public JsonResult ExampleName(string query)
{
if (!string.IsNullOrEmpty(query))
{
//YOUR CODE HERE
return Json(yourDataHere);
}
else
{
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
}
}
And JQuery callback function:
posting.done(function (data) {
//your callback function here
});
That's the trick for JQuery to know what to "grab" from the controller when it returns it. Make sure you return Json(yourDataHere). In case you're wondering, yes, just write 'data' in the function and it will grab yourDataHere from the controller, by itself.
Also, make sure you either have the AntiForgeryToken in both your form and your controller or in none of them. If you have it in your controller only, it will not let you control everything through JQuery.
There is some issues in your javascript.
Try to follow this pattern :
posting.done(function (response) {
var JSONData = JSON.parse(response);
// do something with your json
// ....
// Then append your results in your div.
$('YOUR DIV SELECTOR').html(THAT YOU WANT TO DISPLAY);
});
If you want to return objects and JSON, use a WebAPI controller rather than a surface controller, which will just return an ActionResult. You can get a Surface controller to return JSON, but you'd be better off using an API controller, as that will return JSON objects by default, which is what I assume you're after?
Here's some documentation for WebAPI controllers!

passing multiple object to controller using ajax in ASP.NET MVC

I work on an ASP.NET MVC project.
I have to pass two parameters to an action in my controller. the first is a serializable object, and the second one is an integer.
First time I tried to pass only one parameter, the serializable object. There is no problem, but when I add the second parameter, the serializable object doesn't delivered (null value), but the integer parameter delivered successfully.
this is my action look like :
[HttpPost]
public bool MyAction(MySerializableObject myData, int intParameter)
{..}
and this is how I try to pass the parameters :
$('#submit-button').click(function () {
var formData = $("#MyForm").serialize();
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, { myData: formData, intParameter: '5005' }, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});
});
Anyone can explain about it ? how can it happens and how to solve the problem ?
thanks.
this may be a bit of a longshot but have you tried swapping the order of the parameters around (IE public bool MyAction(int intParameter, MySerializableObject myData) The reason im asking is that it may be that your client side serialize isnt working quite right.
If not your best bet is to take a look at whats actally getting posted to the server. Open up firebugs net tab or similar in webkit and take a look at whats actually going back to the server.
You could use the following plugin (serializeObject) instead of .serialize:
var formData = $('#MyForm').serializeObject();
// add some data to the request that was not present in the form
formData['intParameter'] = 5005;
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, formData, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});

Categories

Resources