Controller doesn't receive one parameter from url query - javascript

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.

Related

How can i use a variable created within a view as an argument within an action result? (ASP.NET MVC)

Within my view i have a piece of JavaScript where i have declared a variable ' Fk '
<script>
function test(clickedID)
{
var Fk = clickedID;
}
</script>
I want to be able to use 'Fk' within an action result by passing it as a parameter.
For example:
[HttpPost]
public ActionResult ReadFk(int Fk) //i would imagine id pass Fk to the ActionResult through the use of its paramaters..?
{
var dataFileFk = Server.MapPath("~/App_Data/ForeignKeyValue.txt");
var textFileDataFk = Fk + Environment.NewLine;
System.IO.File.WriteAllText(dataFileFk, textFileDataFk);
return View();
}
Is there an easy way of doing this?
Thank you!
EDIT:
Since you want to pass a variable from javascript to a controller action and you want to be redirected afterwards, you can use window.location.replace(url)
<script>
function test(clickedID)
{
var Fk = clickedID;
// this will redirect you to a controller action while sending data parameter
window.location.replace("http://yoursite.com/ControllerName/WriteFK?data="+Fk);
}
</script>
Then create an action that will receive the data and write that to the text file;
// remove HttpPost and change to ActionResult
public ActionResult WriteFK(string data)
{
// variable data will contain the FK
// write to text file here
// return view
return View();
}

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 };
}

Asp.Net MVC parameter is null when pass it from client side to controller

Javascript
I have a method as follows,
function OpenRecord(id ,module ,screen) {
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
url = url.replace("_id", encodeURIComponent(id));
url = url.replace("_module", encodeURIComponent(module));
url = url.replace("_screen", encodeURIComponent(screen));
window.location.href = url;
}
Controller
public ActionResult OpenRecord(string id, string module, string screen)
{
Int64 someID = Convert.ToInt64(id);
/*some act**/
return RedirectToAction(screen, module, new { id = someId});
}
When I run this i get id and module but screen param is passed null. When i inspect client side on chrome dev tools, i see all the parameters on javascript method are filled and the final url in url variable as follows;
/Management/OpenRecord/112?module=Customer&screen=MUSTRTANML
I guess that amp&; entity spoils my controller to get the last param but i am not sure and i don't know how to solve this.
Thanks in advance.
Simply wrap your Url.Action in Html.Raw(). Or you can go with replacement approach further - url = url.replace("&", "&"). Whatever you like, personally I would proceed with Html.Raw
you need to construct your url string with values
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
this is wrong, it should be
var url = '/Management/OpenRecord?id=' + _id + '&module='+ _module + '&screen='+ _screen;
the above will pass the values of the variables rather than names , you cannot execute Url.Action as part of JavaScript this is Razor code

MVC send data from View to Controller

I am starting to learn asp.net MVC and probably it's a silly question, but I can't seem to figure out what I am doing wrong.
I have a controller that returns data, between which some variables stored in ViewBag. With the variables stored in the ViewBag, I create a table (they store the number of rows and columns).
[HttpGet]
public ActionResult Index()
{
ViewBag.widht = someNumber1;
ViewBag.height = someNumber2;
return View(someData);
}
[HttpPost]
public ActionResult Index(int someNuber)
{
//calculate the new width and height using someNumber
ViewBag.widht = newWidth;
ViewBag.height = newHeight;
return PartialView();
}
The View has a button, and when the user clicks on it I want to recreate the table with different dimensions.
function OnClick_prev() {
#Html.ActionLink("Index", "Index", new {id = ViewBag.width+5})
}
The problem I have, is that the body of the JavaScript function throws an error (seen in firebug), not really sure why. The error is SyntaxError: syntax error < a href="/Home/Index/36">Index
Any tips?
Change your JS like below
function OnClick_prev() {
var loc = '#Url.Action("Index", "Index", new {id = (int)ViewBag.width+5})';
window.location = loc;
}
The problem is the underlying type of ViewBag is ExpandoObject, ExpandoObject is effectively Dictionary<string, object>, therefore ViewBag.width+5 is the equivalent to
object + int
which won't compile. You will need to cast your width property to int before you perform the calculation
{ id = ((int)ViewBag.width + 5) }
EDIT: just realised my initial answer wouldnt work because you are using POST.
change your GET method to this
[HttpGet]
public ActionResult Index(int id)
{
// Do some check on id to see if it has a value then add your old POST code here
ViewBag.widht = someNumber1;
ViewBag.height = someNumber2;
return View(someData);
}
MVC has default route of
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
so you dont have to pass an id to the method as its optional
then in your view change your code to
#Html.ActionLink("Index", "Index", new {id= (int)ViewBag.width+5})

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

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.

Categories

Resources