如何在MVC视图中使用IF(AND OR)条件?

时间:2016-08-03 21:16:18

标签: asp.net-mvc

如果在我的视图中有条件,我该如何添加?

@if(Model.Remaining > 0 && Model.Total >= 1)
{
/* do something */
}
@if(Model.Remaining > 0 || Model.Total >= 1 || Model.AmountPaid > 100)
{
/* do something */
}

1 个答案:

答案 0 :(得分:2)

if块中放置某种HTML控件,并确保模型上定义的属性值具有将导致if块内的代码呈现的值。

<强>型号:

public class ModelData
{
    public int Remaining { get; set; }
    public int Total { get; set; }
    public decimal AmountPaid { get; set; }
}

<强>控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new ModelData { Remaining = 1, Total = 1, AmountPaid = 99 };
        return View(model);
    }
}

查看:

@model MVCTutorial.Models.ModelData

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Home</title>
</head>
<body>
    @if (Model.Remaining > 0 && Model.Total >= 1)
    {
        <h1>First if...</h1>
    }
    @if (Model.Remaining > 0 || Model.Total >= 1 || Model.AmountPaid > 100)
    {
        <h1>Second if...</h1>
    }
</body>
</html>