简体   繁体   English

根据值通过Html.ActionLink传递参数

[英]Pass parameter with Html.ActionLink based upon value

In my website with paging and search options i have to redirect the user and pass the search options. 在具有分页和搜索选项的网站中,我必须重定向用户并传递搜索选项。 With this action I don't want to pass the search model with the URL (ex. http://localhost:1234/?Project.Models.TestModel=... .). 通过此操作,我不想传递带有URL的搜索模型(例如http:// localhost:1234 /?Project.Models.TestModel =...。 )。

My actionlink right now is as follows: 我现在的动作链接如下:

@Html.ActionLink(i.ToString(), "Index", new { idtrips = Model.idTrips, inituser = Model.initUser, date = Model.date.ToString("ddMMyyyy"), page = i})

When clicked this results in a following header: http://localhost:58763/?idtrips=0&inituser=0&date=05042016&page=5 单击时,将导致以下标题: http:// localhost:58763 /?idtrips = 0&inituser = 0&date = 05042016&page = 5

My question is: Can you somehow add if clauses to the Html.ActionLink to only give values if they are needed. 我的问题是:您能否以某种方式将Html.ActionLink的if子句添加为仅在需要时才提供值。 For example I only have a date set, then I want the Url to be: http://localhost:58763/?date=05042016&page=5 . 例如,我只设置了一个日期,那么我希望Url为: http:// localhost:58763 /?date = 05042016&page = 5 The other values have a default value in my controller so this url will work but i'm not able to generate it. 其他值在我的控制器中具有默认值,因此此url可以工作,但我无法生成它。

My controller: 我的控制器:

public ActionResult Index(long idtrips = 0, long inituser = 0, string date = "", int page = 1)
    { ... }

What i'm looking for is something like this,: 我正在寻找的是这样的:

@Html.ActionLink(i.ToString(), "Index", new { if(Model.idTrips > 0) { idtrips = Model.idTrips,} page = i})

You could probably accomplish this with a ternary statement (eg an inline-if statement) : 您可能可以通过三元语句 (例如inline-if语句)完成此操作:

new { idtrips = Model.idTrips > 0 ? Model.IdTrips : 0, page = i}

Since you have a default parameter value for idtrips , this should only set it to something else if it is greater than 0. 由于您具有idtrips的默认参数值,因此仅应将其设置为大于0的其他值。

If you don't want the value to appear at all, you could consider simply making it a nullable long long? 如果您根本不希望该值出现,则可以考虑将其设置为可为null的long long? parameter (and ensure this matches on your Model as well): 参数(并确保它也与您的模型匹配):

public ActionResult Index(long? idtrips = 0, ... ) { ... }

Using this approach, you could simply set it as expected : 使用这种方法,您可以简单地按预期设置它:

new { idtrips = Model.idTrips, page = i}

And if Model.idTrips was null (eg the default value), then it would point to : 如果Model.idTrips为null(例如默认值),则它将指向:

Controller/Index?page=1

However, if it was any non-null value, it would render the querystring parameter as expected : 但是,如果它是任何非null值,它将按预期方式呈现querystring参数:

Controller/Index?idtrips=42&page=1  

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

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