ASP.NET Core MVC:从视图传递一个参数(来自ViewModel)到控制器

huangapple go评论67阅读模式
英文:

ASP.NET Core MVC : passing one parameter (from ViewModel) from view to controller

问题

在您的Edit方法中,您尝试将字符串参数传递给name,但无论您使用字符串还是视图模型(对象)作为类型,您都收到了null值。

英文:

I'm struggling with one case in my application I've main view when I display for admin user list of parameter.

Of course in my view I use data like a model (two string properties, name and value) and with display everything is ok, but when I click Edit (action link) and I want to pass just name of parameter to my edit method in controller (HttpGet) but I wanted pass string value not int but all the time I get null value in my method.

Can anyone tell me is if it is possible to pass a string parameter from my model?

My code looks something like this:

Viewmodel which I use

@model IEnumerable<ParametersDto>

My action link

@Html.ActionLink("Edit", "Edit", "Parameters", new { id=item.Name })</td>

Code:

[HttpGet]
public IActionResult Edit(string name)        
{
    // ...
}

In my method I tried string and my view model (object) like a type but always I have null value.

答案1

得分: 1

将您的操作方法签名从

public IActionResult Edit(string name)

更改为

public IActionResult Edit(string id)

这样应该允许内置绑定程序填充参数。

英文:

Change your action method's signature from

public IActionResult Edit(string name)

to

public IActionResult Edit(string id) 

That should allow the built in binder to hydrate the argument.

答案2

得分: 0

你的ActionLink 没有正确;你应该像这样修复它:

定义 ActionLink

@Html.ActionLink( linkText,  actionName, controllerName, routeValues, htmlAttributes)

这是正确的代码

@Html.ActionLink(
    "Edit",                  // linkText
    "Edit",                  // actionName
    "orders",                // controllerName
    new {                    // routeValues
        Name = "sds",
        Value = "sds",
    },
    null                     // htmlAttributes
)

这是 Controller 中的 Action 代码

public IActionResult Edit(string Name, string Value)

示例

英文:

Your ActionLink hasn't correct; you should fix it like this:

define ActionLink

@Html.ActionLink( linkText,  actionName, controllerName,    routeValues,htmlAttributes)

this is correct code

@Html.ActionLink(
    "Edit",           // linkText
    "Edit",           // actionName
    "orders",         // controllerName
    new {             // routeValues
        Name ="sds",
        Value ="sds",
    },
    null              // htmlAttributes
)

This is Action Code in Controller

public IActionResult Edit(string Name,string Value)

Examples

huangapple
  • 本文由 发表于 2023年5月11日 03:17:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定