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

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.

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.

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

Model is null when I'm trying to use it in JavaScript

My app arhitecture is ASP.Net MVC
I'm trying to pass some data from the mssql server using entity framework ORM.
This is the code from my action.
public ActionResult Create()
{
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "UserName");
return View(myModel);
}
The code from my view
#model IEnumerable<object>
#{
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
WhereWeDoIt.Models.Place place = Model.ToList()[1] as WhereWeDoIt.Models.Place;
ViewBag.Title = "Create";
}
...
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
...
The console will output "null"
What am I doing wrong?
Once Html.Raw will get the string and put it directly in the html, try
to put the #Html.Raw between single quotes like:
var json = '#Html.Raw(Json.Encode(places))';
Regards,
The solution that I've provided above will set the json to json string (not object) so will not work, sorry about that. Below there is the solution (simulated and tested in my machine)
Well, we have some things going on here.
I have accomplished success in the code doing so:
#model IEnumerable<object>
#{
var places = Model.ToList()[0];
HypothesisWebMVC.Models.Place place = Model.ToList()[1] as HypothesisWebMVC.Models.Place;
ViewBag.Title = "Create";
}
<script type="text/javascript">
//Users data
var json = #Html.Raw(Json.Encode(places));
console.log("Places test " + json);
</script>
This code will set the json variable to a an object (the places list set in the controller).
I don't know what are your goal but that code that I´ve posted above will work.
Some considerations:
In the actions, when you do:
List<object> myModel = new List<object>();
var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());
myModel.Add(places);
myModel.Add(new Place());
You're creating an myModel that will have in the first position and list (or IQueryable) of Place, and in the second position a single place (not a list), so you can not convert the whole model to a list.
You could use:
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
By, when adding to the model, do a .ToList() before inserting.
Consider using a view model (an object created specific for the view)
Hope I've helped.
Regards,
I test your code. Edit view like this:
List<WhereWeDoIt.Models.Place> places = Model.ToList() as List<WhereWeDoIt.Models.Place>;
Model.ToList()[0] is not list.

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