如何在视图中使用2个模型 [英] How to use 2 Models in a View

查看:104
本文介绍了如何在视图中使用2个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在同一个视图中使用两个不同的模型?

How can I use Two different models into the same view?

我为什么需要这个?我需要在客户端填写注册表的地方创建一个create视图,并且我需要有1个组合框/选择表单(此表单需要从其他模型中加载字符串).

Why I need this? I need to do a create view where the client fills his registry, and I need to have 1 combo box/select form(This form needs to load the strings from the other model).

这是我尝试过的:为这两个模型创建一个ViewModel,如下所示:

Here is what I have tried: Creating a ViewModel for both of the Models that looks like this:

   public class CandidateViewModel
{

    public int Id { get; set; }
    public string Name { get; set; }
    public int Number { get; set; }
    public string Profile { get; set; }
    public Byte[] CV { get; set; }
    public string CVNAME { get; set; }
    public List<Profile> ProfileList { get; set; }
    public string ProfileText { get; set; }
}

ProfileList ProfileText 来自 ProfileModel ,其余来自 CandidateModel .

我的控制器现在看起来像这样:

public IActionResult Candidate(Candidate candidate, string searchString)
    {

        using (var aplicationDbContext = new ApplicationContext())
        {
            var candidates = from m in aplicationDbContext.Candidates select m;
            if (!String.IsNullOrEmpty(searchString))
            {
                candidates = candidates.Where(s => s.Name.Contains(searchString) || s.Number.ToString().Contains(searchString) || s.ProfileText.Contains(searchString));
            }
            return View(candidates.ToList());
        }
    }
    public IActionResult CandidateCreate()
    {

        using (var applicationcontext = new ApplicationContext())
        {
            var ProfileTextFromProfile = applicationcontext.Candidates.Include(q => q.ProfileList);
            return View(ProfileTextFromProfile);

        }
        return View();
    }
    [HttpPost, ActionName("CandidateCreate")]
    [ValidateAntiForgeryToken]
    public IActionResult CandidateCreatePost([Bind("Name,Number,Profile,CV,CVID")] Candidate candidate, IFormFile CV,string profileText, int Id)
    {
        if (ModelState.IsValid)
        {
            if (CV != null)
            {
                if (CV.Length > 0)
                {
                    byte[] p1 = null;
                    using (var fs1 = CV.OpenReadStream())
                    using (var ms1 = new MemoryStream())
                    {
                        fs1.CopyTo(ms1);
                        p1 = ms1.ToArray();

                    }
                    candidate.CVNAME = CV.FileName;
                    candidate.CV = p1;
                }
            }
            using (var applicationcontext = new ApplicationContext())
            {
                var ProfileTextFromProfile = applicationcontext.Profile.Include(q => q.ProfileList);

                //var ProfileTextFromProfile = applicationcontext.Profile.Include(q => q.ProfileText).Single(q => q.Id == Id);
                //ProfileTextFromProfile.ProfileText.Add(new Candidate() { Profile = profileText });
            }


            candidateRepository.Add(candidate);
                candidateRepository.SaveChanges();

                return RedirectToAction("Candidate");

        }
        return View();
    }

但是我不知道之后该怎么做,我真的很新,我正在做实习,所以我还在学习,如果对我的问题有任何疑问,请问我,我会尽力解释.

But I don't know what acctually I need to do after this, I'm really new to this and I'm doing this work as an intership soo I'm still learning, If have any doubts about my question please ask me and I will try to explain.

这也是我需要使用这两种模型的视图.

@*model HCCBPOHR.Data.Candidate*@
@model HCCBPOHR.DomainModel.CandidateModel
@{
ViewData["Title"] = "CandidateCreate";
 }
 <h2>CandidateCreate</h2>
 <h4>Candidate</h4>
 <hr />
<div class="row">
<div class="col-md-4">
    <form method="post" enctype="multipart/form-data" asp-action="CandidateCreate">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Name" class="control-label"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Number" class="control-label"></label>
            <input asp-for="Number" class="form-control" maxlength="9" />
            <span asp-validation-for="Number" class="text-danger"></span>
        </div>

        <div class="form-group">
            <label>Selects</label>
            <select asp-for="Profile" class=" form-control ">
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
           </select>
        </div>

        <div class="form-group">
            <label asp-for="CV" type="file" class="control-label"></label>
            <input asp-for="CV" type="file" class="form-control" />
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-default" onclick="this.disabled=true;this.form.submit();" />
        </div>
    </form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>

推荐答案

您可以在这种情况下应用MVVM模式.

You can apply MVVM pattern in this scenario.

以下是示例:

我将在模型"文件夹中定义3个类

I will define 3 class in Model folder

public class Post 
{
   public string Id {get;set;}
   public string Content {get;set;}
   public string UserId {get;set;}
}

public class Comment 
{
  public string Id {get;set;}
  public string Content {get;set;}
  public string PostId {get;set;}
}

// this will hold data for 2 class above
public class PostVM 
{
  public Post Post {get;set}
  public Comment Comment {get;set}
}

然后在我的控制器中,我将查询db以获取用于发布和评论的数据

Then in my controller I will query to db to get data for post and comment like this

public IActionResult PostDetail(string postId)
{
  var post = _postRepository.GetPostById(postId);
  var comment = _commentRepository.GetCommentByPostId(postId);
  // MVVM model return to the view
  var vM = new PostVM 
  {
    Post = post,
    Comment = comment
  }
}

最后在我看来

@model PostVM

<div> @model.Post.Content </div>
@foreach(var comment in @model.Comment)
{
  <div> @comment.Content</div>
}

请根据您的代码进行相应调整.如果您有任何问题,请告诉我.

Please adjust accordingly with your code. If you have any problem please let me know.

欢呼

这篇关于如何在视图中使用2个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆