Как я могу использовать две разные модели в одном представлении?
Зачем мне это нужно? Мне нужно создать представление, в котором клиент заполняет свой реестр, и мне нужно иметь 1 поле со списком / форму выбора (эта форма должна загружать строки из другой модели).
Вот что я пробовал: Создание модели представления для обеих моделей, которая выглядит следующим образом:
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();
}
Но я не знаю, что на самом деле мне нужно делать после этого, я действительно новичок в этом, и я делаю эту работу в качестве стажировки, так что я все еще учусь. Если у меня есть какие-либо сомнения по поводу моего вопроса, пожалуйста, спросите меня и Я постараюсь объяснить.
Также вот мой вид, где мне нужно использовать обе модели.
@*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.
Вот пример:
Я определю 3 класса в папке Model
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, чтобы получить данные для публикации и комментариев, как это
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>
}
Пожалуйста, отрегулируйте соответственно своим кодом. Если у вас возникнут проблемы, дайте мне знать.
Ваше здоровье
У меня проблемы с адаптацией этого к моему коду ... Не могли бы вы мне помочь, поскольку я показал свой контроллер и модели, а также свое представление?
Какая ошибка у вас сейчас? Сделайте снимок экрана с экрана
Это не проблема кода, это проблема логики, не могу придумать, как использовать это в моем коде
Если этот ответ вам поможет, отметьте его, чтобы каждый мог использовать этот ответ как ссылку