我的"数据" Razor语法中的Ajax选项?

时间:2015-05-18 19:52:32

标签: javascript c# ajax asp.net-mvc razor

在文档https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions%28v=vs.118%29.aspx中,我无法找到与data参数相同的内容,例如

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

对表单使用Razor语法,例如

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

我怎么告诉它我想要一个JavaScript变量,比如说,

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

传入相应的控制器

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

??????

2 个答案:

答案 0 :(得分:1)

您可以使用在服务器代码中创建的C#类型将表单数据传递到操作GenerateMasterLink,其中javascript对象中的每个属性都有一个属性。它可能看起来像这样:

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

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

确保发送的数据是有效的JSON(在JavaScript中使用JSON.stringify()将JavaScript对象转换为JSON)。此外,您可以使用ViewBag(或模型)将值放入视图中。以下是您在ViewBag中设置它的方式:

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

然后在剃刀中:

@ViewBag.SomeNameOfYourChoosing

答案 1 :(得分:1)

试试这样。

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

并在控制器中

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

如果您有多个参数,那么

$.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)
{
...
}