将两个参数传递给控制器方法 [英] Pass two parameters to controller method
问题描述
我的默认路线是
My default route is
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
现在在控制器中,我有方法。
Now in the controller, I have the method.
public ActionResult LanguageEdit(int id)
{
视图中的相应代码为:
The corresponding code in the view is:
<div class="widget-content">
@using (Html.BeginForm("Language", "Country", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.HiddenFor(m => m.CountryId)
@Html.Grid(Model.Languages).Columns(column =>
{
column.For(m => m.LanguageName).Named("Languages");
column.For(m => String.Format("<a class='btn btn-primary' href='/Country/LanguageEdit/{0}'>Edit</a> <a href='#deleteConfirmModal' role='button' data-toggle='modal' class='btn btn-danger deleteBtn'><input type='hidden' id='countryId' value='{0}'/>Remove</a>", m.CountryId)).Named("Actions").Encode(false);
}).Attributes(@class => "table")
}
</div>
我们将id(CountryId)传递给方法。
但是出于某种原因,我必须将另一个参数languageId传递给控制器方法。
那么最好的方法是什么?
我试过的:
尝试这个,但仍然不清楚。需要代码帮助。特别是在视图中。
We pass id (CountryId) to the method.
However for some reason, I have to pass another parameter languageId to the controller method.
So what is the best way?
What I have tried:
tried this, but still not clear. Need code assistance. Specifically in the view.
推荐答案
在我看来,传递参数集合的简单方法是创建一个类,其中包含与参数一样多的属性。
例如:
In my opinion the simple way for passing a collection of parameters is create a class that has as many properties as "parameters" do you want.
For example:
public class model1
{
public int param1;
public int param2;
...
}
然后你的控制器应声明为:
And then your controller should be declared as:
public ActionResult LanguageEdit(model1 model)
{
...
model1.param1
...
model2.param2
...
}
在视图中如下:
And inthe view something like:
@Html.HiddenFor(m => m.param1)
...
@Html.TextFor(m => m.param2)
这种类可以扩展到任意类型(或类型)的任何数量的参数
This kind of "class" can be extended to any number of "parameters" of any kind (or type)
抱歉,我没有意识到您没有提交表单,而是提示点击链接。你需要做这样的事情
Sorry I didn't realise you were not submitting the form but rendering a link to click. You'll need to do something like this
column.For(m => String.Format("<a class='btn btn-primary' href='/Country/LanguageEdit/{0}?LanguageId={1}'>Edit</a> <a href='#deleteConfirmModal' role='button' data-toggle='modal' class='btn btn-danger deleteBtn'><input type='hidden' id='countryId' value='{0}'/>Remove</a>", m.CountryId, m.LanguageId)).Named("Actions").Encode(false);
然后改变你的控制器动作
Then change your controller action
public ActionResult LanguageEdit(int id, int? languageId)
{
id将通过路由填充,而languageId通过标准查询字符串值填充
"id" will be populated via routing, and languageId populated via standard querystring values
这篇关于将两个参数传递给控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!