【问题标题】:How can I use Model and viewModel in one file?如何在一个文件中使用 Model 和 viewModel?
【发布时间】:2023-03-21 13:05:02
【问题描述】:

我是一个学习MVC的新手。

我在一个文件中有以下代码

@model  MVCLearn.Models.Customer
@{
    Layout = null;
}    
<!DOCTYPE html>    
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>entercustomer</title>
</head>V
<body>
    <div> 
        @using (Html.BeginForm("submit","Customer",FormMethod.Post))
        {
    <i> Customer code:-</i>
            @Html.TextBoxFor(m=>m.customercode) <br/>
            @Html.ValidationMessageFor(x => x.customercode) <br/>
    <i> Customer name</i> @Html.TextBoxFor(m => m.customername)
            @Html.ValidationMessageFor(x => x.customername) <br/>
            <input id="Submit1" type="submit" value="submit" />
        }
        <br/>         
    </div>
</body>
</html>

现在我想在同一页面中添加一个 viewModel,例如:如果客户名称不是以大写字母开头,则需要显示一条消息。
我在视图模型 MVCLearn.Models.CustomerVM 中编写了一个逻辑。 如何将视图模型添加到此? 当我将相同的内容添加到视图中时,我收到错误“文件中只允许使用一个‘模型’语句。” 如何在文件中添加模型和视图模型?

请帮忙。

【问题讨论】:

  • 您不会在视图中使用数据模型视图模型。只是视图模型。您的视图模型包含与模型相同的属性(只是视图中需要的那些),并使用您需要的验证属性进行装饰。
  • @stephen Muecke 我同意。但是如果我需要编写一个表示逻辑,我该如何处理没有代码的情况呢?
  • 所以我不能在一页中使用模型和视图模型?
  • 你指的是什么表示逻辑?您是否创建了一个ValidationAttribute 来验证customername 属性以大写字母开头?
  • 我需要显示文本颜色根据输入的名称而变化。是的,我在模型中为客户名创建了验证属性。

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 model-view-controller asp.net-mvc-5


【解决方案1】:

您可以像下面的代码一样在 MVC 中使用元组...

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var first = new FirstModel();
        var second = new SecondModel();

        return View(Tuple.Create(first,second));
    }
}

@model Tuple<FirstModel, SecondModel>

<div> 
    @Model.Item1.FirstModelProp
    @Model.Item2.SecondModelProp
</div>

我想它会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2017-09-26
    • 2012-12-01
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    相关资源
    最近更新 更多