简体   繁体   English

使用Jquery检查MVC Model属性是否为空

[英]Check MVC Model property if it's null using Jquery

Ok I have looked a while for some answers to my question but seems like the accepted answers works for some but for me isn't. 好的,我已经看了一段时间才能找到问题的答案,但似乎已接受的答案对某些人有用,但对我而言却不是。

Below is my current implementation to check if @Model.ListImages is not null 下面是我当前的实现,以检查@Model.ListImages是否not null

var img = @((Model != null && Model.ListImages != null).ToString().ToLower());
if (img) {
    if (@Model.ListImages.Count() + this.files.length > 8) {
        this.removeFile(file);
        $('#errorMessage').html("Cannot upload more then 8 images for a product.");
        $("#errorDiv").show();
        window.scrollTo(0, 0);
     }
}

The Model 该模型

public class ProductVM
{
    [Required]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Category")]
    public int IdCategory { get; set; }

    [Required]
    [Display(Name = "Collection")]
    public int IdCollection { get; set; }

    [Required]
    [Range(0.1, 20000, ErrorMessage = "Please enter a value between 0 and 20000")]
    public decimal Price { get; set; }

    [Required]
    [Display(Name = "Product Name")]
    [StringLength(100, ErrorMessage = "Product name must contain at least {2} characters", MinimumLength = 6)]
    public string Name { get; set; }

    [Required]
    [Display(Name = "Product Description")]
    [StringLength(500, ErrorMessage = "Product name must contain at least {2} characters", MinimumLength = 25)]
    public string Description { get; set; }

    public HttpPostedFileBase[] Listfiles { get; set; }


    public virtual IEnumerable<SelectListItem> Categories { get; set; }
    public virtual IEnumerable<SelectListItem> Collections { get; set; }
    public virtual IEnumerable<Reviews> ListReviews { get; set; }
    public virtual ICollection<Images> ListImages { get; set; }

}

The problem is you are mixing JavaScript and Razor which ought to be avoided. 问题是您正在混合使用JavaScript和Razor,应避免使用。 It can be done if done carefully but it leads to hard to read ie hard to debug and maintain. 如果仔细完成,可以完成此操作但会导致难以阅读,即难以调试和维护。

Your code is assuming the Razor will not execute based on JavaScript evaluation. 您的代码假设Razor将不会基于JavaScript评估执行。 However, this is not the case and the Razor statement will always attempt to evaluate. 但是,事实并非如此,Razor语句将始终尝试进行评估。

// this looks like JavaScript with in-lined Razor.
// The Razor is executed before this JavaScript is executed.
var img = @((Model != null && Model.ListImages != null).ToString().ToLower());

// this is a JavaScript conditional based on a run-time value
if (img) {
    // @Model.ListImages.Count() is evaluated by Razor BEFORE
    // (and in a different context) the if(img) above.
    // But there isn't a Razor condition preventing the execution of .Count()
    // if ListImages is not initialized.
    if (@Model.ListImages.Count() + this.files.length > 8) {
         this.removeFile(file);
   }
}

So you need an Razor conditional to output different JavaScript code. 因此,您需要一个Razor条件才能输出不同的JavaScript代码。

@* Razor evaluated on the server while rendering the view *@
@if (Model != null && Model.ListImages != null)
{
    var count = Model.ListImages.Count;
    <script>
        // JavaScript evaluated in the client
        var images = @count;  // "hardcoded" count on the server
        if (images > 0)
        {
            removeFile()
        }
    </script>
}

A cleaner way to avoid the mixing is to encode the Razor value into an HTML element. 一种避免混合的更干净的方法是将Razor值编码为HTML元素。

<div id="image"
     data-count="@((Model != null && Model.ListImages != null) ? Model.ListImages.Count : 0)">
</div>

Then get the value in JavaScript which could run without dynamically outputting different js code. 然后获取JavaScript中的值,该值可以在不动态输出不同js代码的情况下运行。

var count = $("#image").data("count");
if  (count > 0) {
    removeFile();
}
var length = "@(Model.ListImages.Count())";
if(length > 0){
   // do something
}

JavaScript has a tricky (if you don't know it) way of checking conditions for truthy and falsy values. JavaScript有一种棘手的(如果您不知道的话)方式来检查条件的真假值。 When you check for a variable directly in the condition like you did 当您像以前那样直接在条件中检查变量时

if (img)

it doesn't actually check if the value of the variable you provided is false or true, but if that object exists . 它实际上并不会检查您提供的变量的值是false还是true,但是会检查该对象是否存在 So, even if img is false, your code will go there and you'll get a null reference exception. 因此,即使img为false,您的代码也将到达该位置,并且您将获得null reference异常。

Try a simple 尝试简单

if (img != false)

but, as suggested in the other answer, 但是,正如其他答案所建议的那样,

if (@Model && @Model.ListImages && @Model.ListImages.Count() > 0)

is better 更好

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

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