Passing Javascript variable to route value in MVC3 - c#

I would like to pass a javascript variable in a #Url.Action method as a route parameter.
I like to pass the screenmode javascript variable as a route parameter to my action method.
I have a view model with ScreenMode enum property and based on it i
should call a action in Ajax. I also need to pass a javascript
variable as a parameter for route.
This is what i tried and got compilation error.
The name 'screenMode' does not exist in the current context
$("#role-detail-form").submit(function (e) {
if ($(this).valid()) {
var screenMode = 0;
#{
if (Model.ScreenMode == UI.ViewModel.ScreenMode.New)
{
<text>
screenMode =2;
</text>
}
}
$.post('#Url.Action("SaveRoleDetail", new { mode=screenMode})',
$(this).serialize(), function (data) {
$("#role-detail").html(data);
$.validator.unobtrusive.parse($("#role-detail"));
});
}
e.preventDefault();
});
My Action is
public ActionResult SaveRoleDetail(RoleModel viewModel, ScreenMode screenMode)
{
}

You'd have to split that out and build the query string yourself, in order to incorporate the Javascript variable.
Something like this is what you need:
$.post('#(Url.Action("SaveRoleDetail"))?screenMode=' + screenMode)
EDIT: Although probably best practice, you should store the ScreenMode variable in your Model, then put a HiddenFor in your view for it. Then, whenever you change the value in Javascript, simply update the value of the hidden input, that way your action method only needs to take the view model as a parameter. If you are posting the form in JavaScript and you can call $("#form").serialize() to send all the data back within your post call.

Also it's possible to create a place holder and then replace it:
var url = '#Url.Action("GetOrderDetails", "Home", new { id = "js-id" })'
.replace("js-id", encodeURIComponent(rowId));

If you use T4MVC and jQuery, you can call the ActionResult doing the following:
In the controller:
public ActionResult SaveRoleDetail(RoleModel viewModel, ScreenMode screenMode)
{
}
In the view:
$.post("#Url.Action(MVC.Home.SaveRoleDetail())", { viewModel: param1, screenMode: param2) }, function (data) {
//Do Work
});

Access your route values (perhaps in html.HiddenFor). Values from JavaScript and Build your URL without #Url.Action. Use the URL to post.

Related

Sending a string and a model in Url.Action

I have the following URL.Action in my cshtml:
<a href="#Url.Action("ShowStudent", "Student", new { studentCode = item.StudentCode, newPrivateStudent = Model.PrivateStudent })">
<i class="icon-arrow-right"></i>
</a>
The action in my controller is:
public ActionResult ShowCShowStudentlient(studentCode studentCode , PrivateStudentModel newPrivateStudent )
{ *some actions*}
When the action is hit in the controller the newPrivateStudent is set as null.
Any idea why?
The newPrivateStudent properties are set as hidden in the cshtml.
First, you should look at this #Url.Action helper:
#Url.Action("ShowStudent", "Student", new { studentCode = item.StudentCode, newPrivateStudent = Model.PrivateStudent })
The helper above will generate URL with query string like the following example (already tested):
...
As you see at the last parameter (newPrivateStudent), instead of adding contents of the complex object, the helper implicitly calls ToString() which returns fully-qualified name of that object (and subsequently newPrivateStudent has null value in action method). Hence, the proper way to do so is using AJAX callback to post corresponding key together with model contents to controller action and sends back its response as partial view to target DOM element.
Here is an example for sending model contents inside a form with AJAX postback (assumed using HTML helpers to generate input elements):
$('#triggerElementId').click(function () {
// this example sets string parameter as hardcoded string
// change it to actual value by jQuery selector with val() or text() function
var sCode = "XXX";
var modelData = $('form').serialize();
// or serializeArray() if you want to push additional data
// if model contents should left unchanged, use 'var modelData = #Html.Raw(Json.Encode(Model.PrivateStudent))'
$.ajax({
type: 'POST',
url: '#Url.Action("ShowStudent", "Student")',
data: { studentCode: sCode, newPrivateStudent: modelData },
success: function (result) {
$('#targetResultElement').html(result);
},
error: function (xhr, status, error) {
// error handling
}
});
});
Then setting controller action to retrieve key & serialized model contents as in example below:
[HttpPost]
public ActionResult ShowStudent(string studentCode, PrivateStudentModel newPrivateStudent)
{
// some actions
return PartialView("_ShowStudent", viewModelName); // mention partial view & viewmodel name here
}

Pass parameter to jQuery load function in ASP.NET Core

I would like to pass an id parameter from this action in controller
public IActionResult BuildingDetail(int id)
{
return PartialView("_BuildingDetailsPartial", _buildingRepository.GetById(id));
}
into this load method in view to run AJAX.
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/id");
});
})
</script>}
I am new to jQuery, but I guess I need to store id vaule somehow before passing it into load function, so controller/action/parameter approach does not work. But atm I had no luck.
If you want to pass id to the controller via jquery load method, you can pass it directly into the load method as an object.
I assume you have the id's value somewhere on the page or you are hardcoding it in the view using razor syntax from your model.
In any case, try using something like this in your jquery
//passing id's value from the control on the page
$("#BuildingDetail").load("/employees/buildingdetail", { id: $("#Id").val() });
or
//passing id's value from the Model property
$("#BuildingDetail").load("/employees/buildingdetail", { id: #Model.Id });
Reference: jQuery load method

Redirect to MVC ActionResult with Parameters when DropDownList option is changed

I am using MVC to create part of a website. In one of my Views I have a DropDownList. When a new drop down list option is selected, or in other words onchange, I want my page to be redirected to a specific Controller ActionResult. I am able to get to MyAction ActionResult if there are no parameters, however I can't figure out how to send in the needed parameters.
My Controller Action:
public virtual ActionResult MyAction(int param1, int param2)
{
return View();
}
My DropDownList in View:
#Html.DropDownList(
"viewDataItem", Model.MyEnumerableList as SelectList,
new { onchange = #"
var form = document.forms[0];
form.action='MyAction';
form.submit();"
} )
The above code calls MyAction, however it does not send in the parameters. Is there a way to somehow add the parameters to this code?
Another thought was to somehow use #{Response.Redirect(#Url.Action("MyAction", "myController", new { param1 = 2, param2= 3 }));} as my DropDownList action since Response.Redirect allows me to redirect to MyAction with parameters. Is there a way to somehow make onchanged = Response.Redirect?
The tried making onchange equal the response, but the nothing happens when I change my option:
#Html.DropDownList(
"name", Model.MyEnumerableList as SelectList,
new
{
onchange = {Response.Redirect(#Url.Action("MyAction", "controllerName", new { param1 = 5, param2 = 3 }));}
})
In short, how do I call an ActionResult with parameters whenever my DropDownList option is changed?
Similar questions were asked here and here, but the answers provide in those links all use JavaScript and I don't know how to use JS with cshtml. I tried some of those answers, but none of them solved my problems.
You can specify on the onchange event a javascript function and inside that function:
var url = '#Html.Raw(Url.Action("MyAction", "controllerName", new { param1=5, param2=2 }))';
and then:
window.location = url;
Finally the code should be:
#Html.DropDownList(
"viewDataItem", Model.MyEnumerableList as SelectList,
new { onchange = "SelectionChanged()"
} )
<script>
function SelectionChanged()
{
var url = '#Html.Raw(Url.Action("MyAction", "controllerName", new { param1=5, param2=2 }))';
window.location = url;
}
</script>
Is there a way to somehow add the parameters to this code?
Sure, there are many ways. One of them would be:
#Html.DropDownList(
"viewDataItem", Model.MyEnumerableList as SelectList,
new { onchange = #"
var form = document.forms[0];
form.action='MyAction?param1=5&param2=3';
form.submit(); /*Just make sure that form 'method' attribute is set to 'post'*/"
} )
But a much better way is described in the answer you mentioned.
Is there a way to somehow make onchanged = Response.Redirect?
Not the way you're trying to use it. onchanged is a javascript event, and javascript knows nothing about Response property or other MVC server-side stuff.

Calling method from javascript in MVC

I want to call a controller method from Javascript. I used the following code:
<input type="submit" name="button" value="Run" onclick="RunEXE"/>
I want to write the javascript to call the below function in controller.
public void Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
}
Can anyone provide me the javascript to call the function.
You can't just call a function like that. What you need to understand is that javascript runs on the client, and your function is on the server. What you need to do is make a request to the server, just like you would when loading a page, so for this you need an Action (make sure it is a POST action as we will be "posting" the request). This action can be as short as just calling the function you need:
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { #Success = true, #MyString = "a string" });
}
Then you want to use ajax to call the function from the client (javascript), for this I would recommend JQuery as it makes things much easier using post:
$.post('#Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
You can use Ajax here. jQuery ajax is very flexible and easy
Then
prepare your data to post
var myData={};// this is similar to your C# class UserProgram structure
myData.property1=value1; //etc
jQuery.ajax{(
url: '/controllerName/Run/', // or '#Url.Action("Run", "ControllerName")'
type: 'post',
data:{userProgram:myData},
success: function (data) { jQuery('#container').html(data); }
)};
or shorthand
$.post('/controllerName/Run/',{userProgram:myData}, function(result){});
Try this using JQuery:
function RunEXE() {
$.post('#Url.Action("Run", "ControllerName")',
{
userProgram: "WhatEver" //The parameter you want to pass to your action
},
function (data) {
//Code for what to do with the result.
})
};
Use the Normal AJAX method as::
On the Server side(i.e. In Controller) you are using some class/Model like 'UserProgram'
I don't know what are the Properties in that class but I have assumed it as::
public class UserProgram
{
public long ID{get;set}
public string Name{get;set}
}
this Model fields should be based on your Model that you have to pass into your AJAX code as::
var myData={ID:1,Name:"RJ"};
$.ajax{(
type: 'post',
url: '/controllerName/Run'
data:{UserProgram:myData},
success: function (data) {
$('#container').empty();
$('#container').html(data);
}
)};
To get the full description on using ajax calls in ASP.net MVC using jQuery please refer to:
http://bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/

asp.net mvc correctly get json data but can not show on the view page

I am beginner for .net MVC. I guess my problem is related to route setting.
What I want to do is :I get data from database, in controller transfer data to json format and pass to view, use javascript decode json data and show on the html.
When I write methods under TechnologyController, type localhost:portnumber/Technology/Index, no decoded json data in html format, but if I type localhost:portnumber/Technology/GetJson
It show me a page with pure json data (which means if I call GetJson() method separately, it works)
I write the same code in HomeController, it runs correct, all the route setting is default:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
//This is my controller
public class TechnologyController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetJson()
{
Technology myTech = new Technology(); //get data from database (Tested correct)
return Json(myTech.select(), JsonRequestBehavior.AllowGet);
}
}
//This is Javascript:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("Technology/GetJson/", null, function(data) {
sss.innerHTML+=data["title"];// this part is correct (I already tested,please ignore), the purpose is to parse json data to html.
.......
}
)};
)};
I understand if I call "localhost:portnumber/Technology/Index", it only execute index method, that is why GetJson method is not called, but what url should I call in order to call index() as well as GetJson.
something like:
$.getJSON("#Url.Action("GetJson","Technology"), null, function(data) {
edit 2-
Without Razor it would look like this:
$.getJSON("<%= Url.Action("GetJson","Technology") %>, null, function(data) {
Edit-
Wait you want to call Index AND GetJson? That should already be happening, just load the /index page which calls index controller action, then in the rendered script from there your invoking the GJson action. Why would you think you need to call Index again?
I imagine your method isnt getting hit because the url is incorrect. Grab fiddler*, and take a look at the acutal http traffic and see if it is 404'ing on the request.
*(once fiddler is running change your url to http://localhost:port/..... to http://localhost.:port/.....)
I guess you could modify the "index" method inorder to get the data from "GetJSon" method something like below.
public ActionResult Index()
{
return View("GetJson");
}
Hope this helps!!

Categories