69 lines
2.0 KiB
Markdown
69 lines
2.0 KiB
Markdown
|
---
|
||
|
title: "MVC1004: Rename model bound parameter"
|
||
|
description: "Learn about analysis rule MVC1004: Rename model bound parameter"
|
||
|
author: pranavkm
|
||
|
monikerRange: '>= aspnetcore-3.1'
|
||
|
ms.author: riande
|
||
|
ms.date: 10/22/2021
|
||
|
no-loc: [Home, Privacy, Kestrel, appsettings.json, "ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR]
|
||
|
uid: diagnostics/mvc1004
|
||
|
---
|
||
|
# MVC1004: Rename model bound parameter
|
||
|
|
||
|
| | Value |
|
||
|
|-|-|
|
||
|
| **Rule ID** |MVC1004|
|
||
|
| **Fix is breaking or non-breaking** |Breaking|
|
||
|
|
||
|
## Cause
|
||
|
|
||
|
A model bound parameter has the same name as one of its properties.
|
||
|
|
||
|
### Rule description
|
||
|
|
||
|
Model binding a complex parameter with a property that has the same name may result in unexpected binding behavior. Consider renaming the parameter, or using a binding attribute to specify a different name.
|
||
|
|
||
|
Consider the following code:
|
||
|
|
||
|
```csharp
|
||
|
public class HomeController : Controller
|
||
|
{
|
||
|
public IActionResult Get(SearchModel search)
|
||
|
{
|
||
|
...
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public class SearcModel
|
||
|
{
|
||
|
public string Search { get; set; }
|
||
|
}
|
||
|
```
|
||
|
|
||
|
In this model, the parameter and its property are both named `Search`, which results in model binding attempting to bind the property as `search.Search`. Naming a parameter and its property the same prevents binding to a value without a prefix such as a query that looks like `?search=MySearchTerm`.
|
||
|
|
||
|
## How to fix violations
|
||
|
|
||
|
* Rename the parameter if its prefix is not used during binding:
|
||
|
```csharp
|
||
|
public IActionResult Get(SearchModel model)
|
||
|
{
|
||
|
...
|
||
|
}
|
||
|
```
|
||
|
|
||
|
Renaming a parameter on a public type could be considered a breaking change since it changes a library's public API surface.
|
||
|
|
||
|
* If this is problematic, consider using a model binding attribute such as `Bind` to specify the model binding prefix:
|
||
|
|
||
|
```csharp
|
||
|
public IActionResult Get([Bind(Prefix = "")] SearchModel search)
|
||
|
{
|
||
|
...
|
||
|
}
|
||
|
```
|
||
|
|
||
|
## When to suppress warnings
|
||
|
|
||
|
Warnings can be suppressed if you intend to use the parameter name as a prefix during model binding.
|