Where is my “data” Ajax option in Razor syntax?

2019-09-02 08:25发布

问题:

In the documentation https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions%28v=vs.118%29.aspx I can't find anything that is the equivalent of the data parameter in something like

$.ajax({
    url: '@Url.Action("AutoLocate")',
    type: 'GET',
    data: postData,
    success: function(result) {
        // process the results from the controller
    }
});

Using Razor syntax for a form, e.g.

@using (Ajax.BeginForm("GenerateMasterLink", "SurfaceAssets", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "masterLinkHolder" })) { ... }

how do I tell it that I want a JavaScript variable, say,

var str = "here's a string, bro!";

to be passed in to the corresponding controller

public ActionResult GenerateMasterLink (string str)
{
    ...
}

??????

回答1:

Try like this.

$.ajax({
url: '@Url.Action("AutoLocate")',
type: 'GET',
data: str,
success: function(result) {
    // process the results from the controller
}
});

and in controller

public ActionResult GenerateMasterLink (string str)
{
...
}

If you have more than one parameter then

$.ajax({
url: '@Url.Action("AutoLocate")',
type: 'GET',
data: {id: 12,name:'Name'},
success: function(result) {
    // process the results from the controller
}
});

public ActionResult GenerateMasterLink (int id,string name)
{
...
}


回答2:

You can pass form data into the action GenerateMasterLink using a C# type you create in your server code with one property for each of the properties in your javascript object. It might looks something like this:

public class FormData 
{
    public int PropertyName1 { get; set; }
    public string PropertyName2 { get; set; }
}

public ActionResult GenerateMasterLink (FormData form)
{
   ...
}

Make sure the data being sent is valid JSON (use JSON.stringify() in JavaScript to convert a JavaScript object to JSON). Also, you can get the value into your view using the ViewBag (or model). Here's how you'd set it in the ViewBag:

public ActionResult GenerateMasterLink (FormData form)
{
   ViewBag.SomeNameOfYourChoosing = form.PropertyName1;
   return View();
}   

Then in the Razor:

@ViewBag.SomeNameOfYourChoosing