繁体   English   中英

将大量参数传递给控制器​​?

[英]Passing a lot of parameters to a controller?

我正在创建一个“高级输入表单”,其中包含许多用于搜索数据的输入。 我的问题是:从HTML向控制器传递大量数据的最佳方法是什么?

我问的原因是。 假设您有以下HTML表单:

 @using (Html.BeginForm("Loading", "AdvancedSearch"))
    {    
       <input type="text" id="keyword">
       <input type="text" id="keyword1">
       <input type="text" id="keyword2">
       <input type="text" id="keyword3">
       <input type="text" id="keyword4">
       <input type="text" id="keyword5">
       <input type="text" id="keyword6">
       <input type="text" id="keyword7">
       <input type="text" id="keyword8">
       <input type="text" id="keyword9">

       <input type="submit" value="Search" style="width: 150px;" /> 
    }

然后将所有这些都传递给控制器​​是很讨厌的(我有很多关键字):

public ActionResult Loading(string keyword1, string keyword2, string keyword3, string keyword4, string keyword5, string6
                         string keyword7, string keyword8, string keyword9){
//do things to the parameters!
return View();
}

那么,您将如何执行此操作或将您这样做呢?

谢谢!

使用模型类。 只要输入名称与模型属性匹配,MVC引擎将为您完成映射。

public class Keywords
{
    public string keyword1 { get; set; }
    public string keyword2 { get; set; }
    ///etc...
}

而且您的操作要简单得多:

public ActionResult Loading(Keywords keywords){
    //do things to the parameters!
    var keyword1 = keywords.keyword1;
    return View();
}

我建议使用视图模型,并包含关键字列表。 为每个关键字添加属性是没有意义的:

public class Keywords
{
    public List<string> Items { get; set; }
}

public ActionResult Loading(Keywords keywords){ }

或者,如果可能的话:

public ActionResult Loading(List<string> keywords){ }

在这里阅读更多有关它的信息

用那些keyword1,keyword2等创建一个类。

public class SearchDto
{
    public string Keyword1 { get; set; }
    public string Keyword2 { get; set; }
    public string Keyword3 { get; set; }
    public string Keyword4 { get; set; }
    public string Keyword5 { get; set; }
    public string Keyword6 { get; set; }
    public string Keyword7 { get; set; }
    public string Keyword8 { get; set; }
}

然后是ActionResult如

public ActionResult Loading(SearchDto dto)
{
return View();
}

您可以从视图中发布数据。

这里有一个示例,它通过POST(ajax)发送JSON数据并从Controller(MVC)接收JSON响应

还有这里

function search() {
    $.ajax({
        type: "POST",
        url: '@Url.Action("CreateEmail", "Email")',
        data: JSON.stringify({
            Keyword1 : $("#keyword1").val(),
            Keyword2 : $("#keyword2").val(),
            Keyword3 : $("#keyword3").val(),
            Keyword4 : $("#keyword4").val(),
            Keyword5 : $("#keyword5").val(),
            Keyword6 : $("#keyword6").val(),
            Keyword7 : $("#keyword7").val(),
            Keyword8 : $("#keyword8").val(),
        }),
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function (result){
        alert('done');
         }
)};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM