好吧,我已经寻找了一些问题的答案,但似乎接受的答案对某些人有效,但对我来说则不然。
下面是我当前的实现,用于检查@Model.ListImages
是否不为空
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);
}
}
模型
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; }
}
最佳答案
问题是你正在混合 JavaScript 和 Razor,这是应该避免的。如果仔细可以完成,但它会导致难以阅读,即难以调试和维护。
您的代码假设 Razor 不会根据 JavaScript 评估执行。然而,情况并非如此,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);
}
}
因此您需要一个 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>
}
避免混合的一种更简洁的方法是将 Razor 值编码到 HTML 元素中。
<div id="image"
data-count="@((Model != null && Model.ListImages != null) ? Model.ListImages.Count : 0)">
</div>
然后获取JavaScript中的值,无需动态输出不同的js代码即可运行。
var count = $("#image").data("count");
if (count > 0) {
removeFile();
}
关于javascript - 使用 Jquery 检查 MVC 模型属性是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201082/