asp.net-mvc 将多个参数传递给控制器​​?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1126141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:43:04  来源:igfitidea点击:

Passing multiple parameters to a controller?

asp.net-mvc

提问by satish

ok. simple one that is wrapping my brain

好的。一个简单的包裹着我的大脑

I have a method that I have in the controller

我在控制器中有一个方法

public ActionResult Details(string strFirstName, string strLastName)
{
      return View(repository.getListByFirstNameSurname(strFirstName, strLastName)
}

How do i get multiple parameters from the URL to the controller?

如何从 URL 获取多个参数到控制器?

I dont want to use the QueryString as it seems to be non-mvc mind set.

我不想使用 QueryString 因为它似乎是非 mvc 思维定势。

Is there a Route? Or Other mechanism to make this work? Or am I missing something altogehter here with MVC

有路线吗?或其他机制使这项工作?或者我在这里错过了 MVC 的全部内容

EDIT

编辑

the url that I am trying for is

我正在尝试的网址是

http://site.com/search/details/FirstName and Surname

so if this was classic asp

所以如果这是经典的asp

http://site.com/search/details?FirstName+Surname

But i feel that i have missed understood something which in my haste to get to working code, I have missed the point that there really should be in a put request - and I should collect this from the formcollection.

但是我觉得我错过了在我匆忙开始工作代码时理解的东西,我错过了真正应该在 put 请求中存在的点 - 我应该从 formcollection 中收集它。

Though might be worth while seeing if this can be done - for future reference =>

虽然可能值得看看这是否可以完成 - 以供将来参考 =>

采纳答案by San

Use hidden values in your form

在表单中使用隐藏值

<%= Html.Hidden("strFirstName", Model.FirstName)%>
<%= Html.Hidden("strLastName", Model.LastName)%>

and the model binder will do the binding

并且模型绑定器将进行绑定

public ActionResult Details(string strFirstName, string strLastName)
{
      return View(repository.getListByFirstNameSurname(strFirstName, strLastName)
}

回答by satish

For example, suppose that you have an action method that calculates the distance between two points:

例如,假设您有一个计算两点之间距离的操作方法:

public void Distance(int x1, int y1, int x2, int y2)
{
   double xSquared = Math.Pow(x2 - x1, 2);
   double ySquared = Math.Pow(y2 - y1, 2);
   Response.Write(Math.Sqrt(xSquared + ySquared));
}

Using only the default route, the request would need to look like this:

仅使用默认路由,请求将需要如下所示:

/simple/distance?x2=1&y2=2&x1=0&y1=0

We can improve on this by defining a route that allows you to specify the parameters in a cleaner format.

我们可以通过定义一个允许您以更清晰的格式指定参数的路由来改进这一点。

Add this code inside the RegisterRoutesmethods within the Global.asax.cs.

将此代码添加RegisterRoutesGlobal.asax.cs.

routes.MapRoute("distance",
"simple/distance/{x1},{y1}/{x2},{y2}",
new { Controller = "Simple", action = "Distance" }
);

We can now call it using /simple/distance/0,0/1,2

我们现在可以使用 /simple/distance/0,0/1,2

回答by eu-ge-ne

Something like this?:

像这样的东西?:

routes.MapRoute("TheRoute",
    "{controller}/{action}/{strFirstName}/{strLastName}",
    new { controller = "Home", action = "Index", strFirstName = "", strLastName = "" }
);

or:

或者:

routes.MapRoute("TheRoute2",
    "people/details/{strFirstName}/{strLastName}",
    new { controller = "people", action = "details", strFirstName = "", strLastName = "" }
);

UPDATED:

更新:

This route should be placed before "Default" route:

这条路线应该放在“默认”路线之前:

// for urls like http://site.com/search/details/FirstName/Surname
routes.MapRoute("TheRoute",
    "search/details/{strFirstName}/{strLastName}",
    new { controller = "search", action = "details", strFirstName = "", strLastName = "" }
);

routes.MapRoute("Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" }
);

回答by Peter J

It is also possible to use FormCollection:

也可以使用 FormCollection:

public ActionResult Details(int listId, FormCollection form)
{
  return View(rep.getList(form["firstName"], form["lastName"])
}

Likewise, if the HTTP request contains a form value with the exact same name (case sensitive), it will automatically be passed into the ActionResult method.

同样,如果 HTTP 请求包含具有完全相同名称的表单值(区分大小写),它将自动传递到 ActionResult 方法中。

Also, just to be clear, there is nothing un-MVC about querystring parameters.

另外,要清楚的是,查询字符串参数没有任何非MVC。

回答by Dushantha

I also had the same problem once and what I did was use the Ajax call inside the jQuery function. First I selected all parameter values using jQuery selectors. Below is my jQuery function.

我也遇到过同样的问题,我所做的是在 jQuery 函数中使用 Ajax 调用。首先,我使用 jQuery 选择器选择了所有参数值。下面是我的 jQuery 函数。

<script language="javascript" type="text/javascript"> 
 $(document).ready(function () {
    $('#btnSendNow').click(function () {
    var grid = $('#Patient-kendo-Grid').data('kendoGrid');
    var location = $('#EmailTempalteLocation option:selected').text();
    var appoinmentType = $('#EmailTemplateAppoinmentType option:selected').text();
    var emailTemplateId = $('#EmailTemplateDropdown').val();
    var single = $('input:radio[name=rdbSingle]:checked').val();
    var data = grid.dataSource.view();
    var dataToSend = {
    patients: data,
    place: location,
    appoinment: appoinmentType,
    rdbsingle: single,
    templateId: emailTemplateId
    };
    debugger;
    $.ajax({
    url: 'Controller/Action',
    type: 'post',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(dataToSend)
    });
    });
    });
</script>

My controller method has five parameters and it is as below.

我的控制器方法有五个参数,如下所示。

[HttpPost]
public ActionResult SendEmailToMany(List<PatientModel> patients, string place, string appoinment, string rdbsingle, string templateId)
{ 
emailScheduleModel = new EmailScheduleModel();
AmazonSentEmailResultModel result;
List<string> _toEmailAddressList = new List<string>();
List<string> _ccEmailAddressList = new List<string>();
List<string> _bccEmailAddressList = new List<string>();
IEmailTemplateService emailTemplateService = new EmailTemplateService();
EmailTemplateContract template = emailTemplateService.GetEmailTemplateById(new       Guid(templateId));
emailScheduleModel.EmailTemplateContract = new EmailTemplateContract();
emailScheduleModel.EmailTemplateContract = template;
}

It is working fine in my developments.

它在我的开发中运行良好。

For further details please follow the below url.
http://dushanthamaduranga.blogspot.com/

欲了解更多详情,请关注以下网址。
http://dushanthamaduranga.blogspot.com/