简体   繁体   English

区分ASP.NET MVC4中的null和missing参数

[英]Distinguish between null and missing parameters in ASP.NET MVC4

I'm writing an API. 我正在写一个API。 I want to allow a PUT method to update a resource. 我想允许PUT方法更新资源。 Below is an example model object representing the resource- 下面是一个表示资源的示例模型对象 -

var resourceToUpdate = new TestResourceModel() 
    {
        Id = 5
        Name = "testName",
        Description = "description",
        etc...
    }

I want a client to be able to PUT to /TestResource/5 to update properties on the resource 我希望客户端能够PUT到/ TestResource / 5来更新资源的属性

Now, say that the client only wants to update property Name, but not description so sends the following request: 现在,假设客户端只想更新属性Name,而不是更新描述,因此发送以下请求:

Name="testNewName"

In this case, the resource should be updated so Name is now "testNewName", put Description is still "description" 在这种情况下,资源应该更新,因此Name现在是“testNewName”,put描述仍然是“描述”

How do I distinguish this case (in my Controller method), from the case where the client wants to set the Description property to null: 我如何区分这种情况(在我的Controller方法中),以及客户端想要将Description属性设置为null的情况:

Name="testNewName"
Description=

as my controller method will look like: 因为我的控制器方法看起来像:

[HttpPut]
public ActionResult Index(TestResourceModel model)
{
    //True in both cases
    bool descriptionSet = model.Description == null;

Well you have to compare the incoming values with the values you want to update.. I mean null is null is null :) Alt. 那么你必须将传入的值与你想要更新的值进行比较。我的意思是null是null是null :) Alt。 set an update flag in your model (bool isUpdate) then only change the values that isn't null. 在模型中设置更新标志(bool isUpdate),然后仅更改非空值。

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

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