Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.
Here is what I am trying to do:
#Html.Action("someAction", "someController", new { passedData = GetDropDownData() })
<script>
function GetDropDownData() {
var data = "test";
return data;
}
</script>
Basically I am trying to pass some drop down data from a control to a partial view being rendered with the #Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?
Let me know if you have any suggestions or a better way to go about this.
Thank you!
This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:
<a href='#' id='clickMe'>Click me</a>
And hooking up jQuery to do the job:
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
passedData: GetDropDownData()
},
success: function(response){
$('#placeholderForPartialView').html(response);
}
});
});
});
</script>
It would look something like this depending on your method (GET or POST) type.
Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.
The reply at
MVC3 Pass Model view to controller using javascript
implies that this was impossible, at least for MVC 3.
I was wondering if there is any way in MVC 4 to quickly pass the entire form contents (represented by the model) from the .cshtml (razor) view to the controller in JavaScript.
For example, if I select a dropdown, I may want to return all fields from a form to the controller which will take appropriate action.
Obviously, for large forms it is undesirable to have to do this element-by-element
Basically, you can do it calling an AJAX POST:
JS (using jQuery):
$('form').on('submit', function (event) {
// Stop the default submission
event.preventDefault();
// Serialize (JSON) the form's contents and post it to your action
$.post('YourAction', $(this).serialize(), function (data) {
// If you want to do something after the post
});
});
Controller Action:
public ActionResult YourAction(string JSONmodel)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
MyModel model = serializer.Deserialize(JSONmodel, typeof(MyModel));
// Now you can do whatever you want with your model
}
UPDATE
For more complex objects, you can use a third part solution for serialization/deserialization. It's well documented and broaden used:
Json.NET: http://json.codeplex.com/
Yes it is possible in a simpler way.
Alternate of example provided by MelanciUK.
$('form').on('submit', function (event) {
// Stop the default submission
event.preventDefault();
// User same property name as in Model
$.post('YourAction', {prop1 : 'a', prop2 : 'b'}, function (data) {
// If you want to do something after the post
});
});
[HttpPost]
public ActionResult SampleAction(SampleModel sModel)
{
}
You can achieve the same thing by stadard MVC(ModelBinding) convention i.e. no need to serialize and deserialize.
I am working a site in ASP.NET MVC where the user is presented with a calendar, and clicking on a particular calendar date invokes the following function:
function selectHandler(event, data) {
var myRequest = new Request.HTML({
url: '/Calendar/EventList',
method: 'post',
data: { datedata: data.toString() },
update: $('postback'),
}).send();
};
I am using the MooTools AJAX classes to invoke my Controller Action /Calendar/EventList, shown below:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EventList(string datedata)
{
CalendarViewData viewData = new CalendarViewData
{ EventList = GetEventsList(datedata) };
return View(viewData);
}
I can set a breakpoint in the EventList action, and see that it is returning the view, but the browser remains on the initial page, and never redirects to the page returned by this EventList action.
I suspect I need to add more to my JavaScript function but am not sure what. Any ideas?
Why would the browser redirect? You are sending an AJAX request to a controller action which returns a view (this probably is wrong, you might need to return a partial view) which is then used to update some element in the DOM. If you want to redirect you could use a simple anchor tag (or a form if you need to POST), no need to use javascript.
Can I call javascript function from MVC controller action (not from view page) and get return value? How?
I need to make request to server from code (.cs) using javascript like here (but this is aspx page)
function getInitData() {
var code; code = 'return {' ;
code += 'me: API.getProfiles({uids: API.getVariable({key: 1280}), fields: "photo"})[0]';
code += '};'
VK.Api.call('execute', { 'code': code }, onGetInitData);
}
For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.
First, create a string property on your Model.
public class MyModel
{
public string JavascriptToRun { get; set;}
}
Now, bind to your new model property in the Javascript of your view:
<script type="text/javascript">
#Model.JavascriptToRun
</script>
Now, also in your view, create a Javascript function that does whatever you need to do:
<script type="text/javascript">
#Model.JavascriptToRun
function ShowErrorPopup() {
alert('Sorry, we could not process your order.');
}
</script>
Finally, in your controller action, you need to call this new Javascript function:
[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
// Do something useful
...
if (success == false)
{
model.JavascriptToRun= "ShowErrorPopup()";
return View(model);
}
else
return RedirectToAction("Success");
}
You can call a controller action from a JavaScript function but not vice-versa. How would the server know which client to target? The server simply responds to requests.
An example of calling a controller action from JavaScript (using the jQuery JavaScript library) in the response sent to the client.
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
error : function(req, status, error) {
// do something with error
}
});
Yes, it is definitely possible using Javascript Result:
return JavaScript("Callback()");
Javascript should be referenced by your view:
function Callback(){
// do something where you can call an action method in controller to pass some data via AJAX() request
}
It is late answer but can be useful for others.
In view use ViewBag as following:
#Html.Raw("<script>" + ViewBag.DynamicScripts + "</script>")
Then from controller set this ViewBag as follows:
ViewBag.DynamicScripts = "javascriptFun()";
This will execute JavaScript function.
But this function would not execute if it is ajax call.
To call JavaScript function from ajax call back, return two values from controller and write success function in ajax callback as following:
$.ajax({
type: "POST",
url: "/Controller/Action", // the URL of the controller action method
data: null, // optional data
success: function(result) {
// do something with result
},
success: function(result, para) {
if(para == 'something'){
//run JavaScript function
}
},
error : function(req, status, error) {
// do something with error
}
});
from controller you can return two values as following:
return Json(new { json = jr.Data, value2 = "value2" });
There are ways you can mimic this by having your controller return a piece of data, which your view can then translate into a JavaScript call.
We do something like this to allow people to use RESTful URLs to share their jquery-rendered workspace view.
In our case we pass a list of components which need to be rendered and use Razor to translate these back into jquery calls.
If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt)
So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:
void webBrowser1_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
if(search != null)
{
search.SetAttribute("value", "Superman");
foreach(HtmlElement ele in search.Parent.Children)
{
if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
{
ele.InvokeMember("click");
break;
}
}
}
}
So probably nowadays, that would not be the easiest solution.
The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.
Some related questions on this topic or possible duplicates:
Embedding JavaScript engine into .NET
Load a DOM and Execute javascript, server side, with .Net
Hope this helps.
The usual/standard way in MVC is that you should put/call your all display, UI, CSS and Javascript in View, however there is no rule to it, you can call it in the Controller as well if you manage to do so (something i don't see the possibility of).
Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.
<script>
$(document).ready(function () {
var msg = '#ViewBag.ErrorMessage'
if (msg.length > 0)
OnFailure('Register', msg);
});
function OnSuccess(header,Message) {
$("#Message_Header").text(header);
$("#Message_Text").text(Message);
$('#MessageDialog').modal('show');
}
function OnFailure(header,error)
{
$("#Message_Header").text(header);
$("#Message_Text").text(error);
$('#MessageDialog').modal('show');
}
</script>
I want to preface that I know this question has been asked before, but I haven't found a concrete answer that works on .NET core.
I am trying to pass a Model Value back to my controller so I can do some work on it. Can I use Razor URL helpers to send the URL as #Url.Action("Action", "Controller") within the .ajax URL? Also, how can I send data to do work on async? Here is my script file:
$('#ajaxBtn').on('click', function (e) {
$.ajax({
url: "/Home/AjaxReturn",
type: "POST",
dataType: "json",
data: 'data: 12345',
success: function () {
}
});
});
Here is my Controller code:
[HttpPost]
public void AjaxReturn(JsonResult data)
{
var thisData = data;
}
** I am using this for a responsive js datatable (datatables.net) eg. on a DELETE click I want to pass the ID back to the controller so I can delete the record and then pass back a status.
try to change the parameter in your ajax code.
data: '"data": "12345"',