Dorin Munteanu
Dorin Munteanu

Reputation: 103

How to use 2 Models in a View

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

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).

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 and ProfileText are from ProfileModel, the rest is from the CandidateModel.

My controller right now looks like this:

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.

Also here is my View where I need to use both of the models.

@*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>

Upvotes: 0

Views: 98

Answers (1)

user4851087
user4851087

Reputation:

You can apply MVVM pattern in this scenario.

Here is example:

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}
}

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
  }
}

Finally in my view

@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.

Cheers

Upvotes: 3

Related Questions