什么时候我应该在我的控制器动作中使用nullable int以及它在asp.net mvc 5中的用途

时间:2022-12-04 16:42:52

At many places I see controller action with Nullable Int as parameter. I have known from SO research that I should put Model Propetry as Nullable and Required. It helps to protect from Underposting attack and also, it helps us to avoid seeing "Default values" of property in UI Form, such as for datetime property.

在许多地方,我看到Nullable Int作为参数的控制器动作。我从SO研究中得知,我应该将Model Propetry设为Nullable和Required。它有助于防止Underposting攻击,也有助于我们避免在UI Form中看到属性的“默认值”,例如datetime属性。

[Required]
public DateTime? dateTime {get;set;}

With above set up I will now not see the defaulted date. So far so good. But what is the significance of using "?" in ControllerAction? And when shall I use it.

通过以上设置,我现在看不到默认日期。到现在为止还挺好。但是使用“?”有什么意义呢?在ControllerAction中?我何时才能使用它。

Currently, I have a Delete functionality and I have written below code

目前,我有一个删除功能,我写了下面的代码

  [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int? resumeId)
        {
            var r = _context
                .Resumes
                .Where(c => c.ResumeId == resumeId).SingleOrDefault();
            _context.Resumes.Remove(r);
            _context.SaveChanges();

            return RedirectToAction("ResumeCenter");
        }

Can someone guide me on when do I need to use "?" and it's significance? I read this Nullable Int link, but I could not understand. Kindly give me an example for both usage.

有人可以指导我何时需要使用“?”它有意义吗?我读了这个Nullable Int链接,但我无法理解。请给我一个两种用法的例子。

3 个解决方案

#1


1  

There is no value in making the parameter nullable in your case. Its a POST method for deleting a record based on its Id so your expecting an Id to be provided, and a null value would make no sense.

在您的情况下,使参数可以为空是没有价值的。它是一种POST方法,用于根据其Id删除记录,因此您希望提供Id,而空值则没有意义。

What however you should be doing is checking that the current user has the permission to delete a record with that Id, and checking that the record returned by your query is not null before calling the context to delete the record so that you protected against malicious users (or the case where another user may have deleted the same record in the meantime).

但是你应该做的是检查当前用户是否有权删除具有该Id的记录,并在调用上下文删除记录之前检查查询返回的记录是否为null,以便防止恶意用户(或者其他用户可能在此期间删除了相同记录的情况)。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int resumeId)
{
    ... // check if the user has permission to delete the Resume with this id
    var r = _context.Resumes.Where(c => c.ResumeId == resumeId).SingleOrDefault();
    if (r != null)
    {
        _context.Resumes.Remove(r);
        _context.SaveChanges();
    }
    return RedirectToAction("ResumeCenter");
}

Note that the example you linked to is a GET method, and it may be appropriate to have nullable parameters, for example a method that filters a set of records based on a CategoryId where a value of null means return all records, as opposed to returning only records that have the matching CategoryId

请注意,您链接到的示例是GET方法,可能适合使用可为空的参数,例如,基于CategoryId过滤一组记录的方法,其中值null表示返回所有记录,而不是返回只有具有匹配CategoryId的记录

#2


0  

I sometimes use it, in more complex controller action methods, where there is the possibility that a person did or did not selected something on the page.

我有时会在更复杂的控制器动作方法中使用它,在这种方法中,一个人可能会在页面上选择或未选择某些内容。

In this case you want to show something else if they provided an int or not, without having multiple pages.

在这种情况下,如果他们提供了int或不提供int,则需要显示其他内容,而不需要多个页面。

Another argument could be a page (think: ...controller/products?id=7) which people can share in apps or social media, where the latter part (?id=xxx) can be forgotten. In that case you will display an error page to a possible customer. What you want to do is catch that null value and redirect the user to the overview page, instead of a specific product page.

另一个论点可能是一个页面(想想:... controller / products?id = 7),人们可以在应用程序或社交媒体上分享,后者(?id = xxx)可能会被遗忘。在这种情况下,您将向可能的客户显示错误页面。您要做的是捕获该空值并将用户重定向到概述页面,而不是特定的产品页面。

And as said by others and felt by you, for your example it does not make a lot of sense.

正如其他人所说并且你感受到的那样,对于你的例子来说,它没有多大意义。

#3


-1  

Ok, look here. You have route like this: .../Products/Update?id=0 So if param id is null or id==0 you create product else you update product.

好的,看这里。你有这样的路线:... / Products / Update?id = 0所以如果param id为null或id == 0你创建产品,你更新产品。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Update(int? id=0)
    {
        if(id==0) create something else update 

        return RedirectToAction("ResumeCenter");
    }

int? id=0 mean that if action do not take any argument id becomes equal 0. It`s mean that this param is optional.

诠释? id = 0表示如果action不接受任何参数id变为等于0.这意味着该param是可选的。

#1


1  

There is no value in making the parameter nullable in your case. Its a POST method for deleting a record based on its Id so your expecting an Id to be provided, and a null value would make no sense.

在您的情况下,使参数可以为空是没有价值的。它是一种POST方法,用于根据其Id删除记录,因此您希望提供Id,而空值则没有意义。

What however you should be doing is checking that the current user has the permission to delete a record with that Id, and checking that the record returned by your query is not null before calling the context to delete the record so that you protected against malicious users (or the case where another user may have deleted the same record in the meantime).

但是你应该做的是检查当前用户是否有权删除具有该Id的记录,并在调用上下文删除记录之前检查查询返回的记录是否为null,以便防止恶意用户(或者其他用户可能在此期间删除了相同记录的情况)。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int resumeId)
{
    ... // check if the user has permission to delete the Resume with this id
    var r = _context.Resumes.Where(c => c.ResumeId == resumeId).SingleOrDefault();
    if (r != null)
    {
        _context.Resumes.Remove(r);
        _context.SaveChanges();
    }
    return RedirectToAction("ResumeCenter");
}

Note that the example you linked to is a GET method, and it may be appropriate to have nullable parameters, for example a method that filters a set of records based on a CategoryId where a value of null means return all records, as opposed to returning only records that have the matching CategoryId

请注意,您链接到的示例是GET方法,可能适合使用可为空的参数,例如,基于CategoryId过滤一组记录的方法,其中值null表示返回所有记录,而不是返回只有具有匹配CategoryId的记录

#2


0  

I sometimes use it, in more complex controller action methods, where there is the possibility that a person did or did not selected something on the page.

我有时会在更复杂的控制器动作方法中使用它,在这种方法中,一个人可能会在页面上选择或未选择某些内容。

In this case you want to show something else if they provided an int or not, without having multiple pages.

在这种情况下,如果他们提供了int或不提供int,则需要显示其他内容,而不需要多个页面。

Another argument could be a page (think: ...controller/products?id=7) which people can share in apps or social media, where the latter part (?id=xxx) can be forgotten. In that case you will display an error page to a possible customer. What you want to do is catch that null value and redirect the user to the overview page, instead of a specific product page.

另一个论点可能是一个页面(想想:... controller / products?id = 7),人们可以在应用程序或社交媒体上分享,后者(?id = xxx)可能会被遗忘。在这种情况下,您将向可能的客户显示错误页面。您要做的是捕获该空值并将用户重定向到概述页面,而不是特定的产品页面。

And as said by others and felt by you, for your example it does not make a lot of sense.

正如其他人所说并且你感受到的那样,对于你的例子来说,它没有多大意义。

#3


-1  

Ok, look here. You have route like this: .../Products/Update?id=0 So if param id is null or id==0 you create product else you update product.

好的,看这里。你有这样的路线:... / Products / Update?id = 0所以如果param id为null或id == 0你创建产品,你更新产品。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Update(int? id=0)
    {
        if(id==0) create something else update 

        return RedirectToAction("ResumeCenter");
    }

int? id=0 mean that if action do not take any argument id becomes equal 0. It`s mean that this param is optional.

诠释? id = 0表示如果action不接受任何参数id变为等于0.这意味着该param是可选的。