How can we send data back to Controller action from Javascript
I have a modal dialog box which would open onclick开发者_JAVA百科 of a link in the page. From the js now i would need to send some values to the Controller. But I cannt use form from where I can submit those values back to controller. Are there any other way of doing this or am I talking insane??
You can use the methods as No Refunds No Returns explains but rather than pass back numerous params you can build your own class to pass back.
E.g. if you were passing back details of a job you could have a class called Job with parameters of Salary, Hours, Title, Department etc.
public class Job
{
public float Salary {get; set;}
public float Hours {get; set;}
public string Title {get; set;}
public string Department {get; set;}
}
You can then make a controller method that takes in an object of type Job.
public ActionResult DoSomething(Job theJob)
{}
Then in javascript you can build up a JSON object, with key value pairs. The key being the name of the parameter.
var data = {
Salary: 400,
Hours: 40,
Title: 'Developer',
Department: 'I.T.'
};
You can then pass this object to the controller method and the values will be mapped to the Job object which you can then use in your controller method.
data comes back via the URL. You update your route to identify the parameters and build your URL to match.
route is like {controller}/{action}/{id}/{parameter1}/{parameter2}/
You can also create a catchall parameter like
route is like {controller}/{action}/{id}/{*parameters}/
then build a URL like yoursite.com/Accounts/DIsplay/Fred/june/july parametesr will be june/july which you can build on your URL.
Check my syntax to be sure since I'm doing this while eating breakfast. :)
Using JQuery, you can use:
$.get $.post $.ajax
And post data back to the server. This all happens asynchronously to the user. See jquery.com for how to use, it's really easy. Using the URL, it will know which controller/action to get or post data to; it works very well.
Get's use the URL to pass data back to the server, while post's use a form and submit the form fields to the server. So it depends how you want to pass the data. Using the Html.BeginForm and Html.EndForm, you define the form and the values within it are posted to the server, which all values can be retrieved by specifying a FormCollection collection as the action method parameter, or an object type which has method names the same as the object's properties itself, or it will pass these values to variables too. It does name matching to do all of this, regardless of a get or a post operation.
So this can be done in MVC with a postback, or using JQuery asynchronously.
精彩评论