كيفية تعيين صورة افتراضية إذا كانت قيمة src للصورة فارغة في ASP.NET
To set a default image if the src
attribute is null or empty, you can use the ImageUrl
property of an asp:Image
control in ASP.NET. Here’s how you can do it:
csharp"Image1" runat="server" ImageUrl='<%# string.IsNullOrEmpty(Eval("Data").ToString()) ? "~/images/myimage.png" : Eval("Data").ToString() %>' />
In this example, if the Data
field is null or empty, the ImageUrl
will be set to "~/images/myimage.png"
. Otherwise, it will use the value of the Data
field. Note that you need to use the Eval
method to access the field value in the data-binding expression.
-
تحديث قيمة maxCarryOns في Java24/03/2024
-
إدارة تصدير المتغيرات في باش: أساليب وتقنيات06/02/2024
-
حذف الروابط المحظورة من مصفوفة الروابط19/03/2024
-
Git: تعقب التغييرات بدقة05/03/2024
If you’re using an img
tag directly instead of an asp:Image
control, you can achieve the same result using inline code:
csharp'<%# string.IsNullOrEmpty(Eval("Data").ToString()) ? "~/images/myimage.png" : Eval("Data").ToString() %>' style="width:100%; height:30%;" />
This code checks if the Data
field is null or empty and sets the src
attribute to "~/images/myimage.png"
if true, or to the value of the Data
field otherwise.
المزيد من المعلومات
بالتأكيد! في هذا السياق، نستخدم تعبير الشرط المدمج (ternary operator) ? :
لفحص إذا كانت قيمة الحقل Data
فارغة أم لا. إذا كانت فارغة، سنقوم بتعيين قيمة ال ImageUrl
إلى المسار ~/images/myimage.png
كصورة افتراضية، وإلا سنقوم باستخدام قيمة ال Data
لتحديد مسار الصورة. تحتوي العبارة على الجزء الأول string.IsNullOrEmpty(Eval("Data").ToString())
الذي يفحص إذا كانت قيمة ال Data
فارغة أم لا، ثم يعيد القيمة المناسبة (true
أو false
). الجزء الثاني من التعبير ?
يحدد القيمة التي ستُعين في حال كانت القيمة السابقة true
، في حين يحدد الجزء الثالث :
القيمة التي ستُعين إذا كانت القيمة السابقة false
.