0

I have two db classes one Tasks and second AssignedTasks and I want to use it in one view when the admin creates the task then he/she assigned the task parallelly in spite of first creating the view and then assigned task to employee but I didn't get how to do it as I am new in asp.net can anybody please help me through example code ? my code is as follows

  public partial class Task
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Task()
    {
        this.AssignedTasks = new HashSet<AssignedTask>();
    }

    public int TaskId { get; set; }
    public string TaskName { get; set; }
    public System.DateTime TaskDeadLine { get; set; }
    public int TaskNumber { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<AssignedTask> AssignedTasks { get; set; }
}

and the code of assigned task is

  public partial class AssignedTask
{
    public int AssignId { get; set; }
    public int AccountId { get; set; }
    public int TaskId { get; set; }

    public virtual Account Account { get; set; }
    public virtual Task Task { get; set; }
}

The AssignedTask class has the foriegn key of task.

Ant P
  • 24,820
  • 5
  • 68
  • 105
Arslan Afzal
  • 95
  • 2
  • 13
  • 1
    You need to create a *view model* class that has all of the properties that are needed for the *view*. Then you map all of the information from the two DB objects to the *view model* and pass *that* to your view instead. This is a *very* common beginner MVC question so googling around for view models will generate lots of good information for you if you need more clarification on the concept. – Ant P May 05 '16 at 07:48
  • 1
    Also note that you **really** should avoid passing DB classes directly to views altogether unless you know what you're doing - it opens the door to vulnerabilities because anyone can easily change any property on the class in a POST request (just by submitting a form with the right fields to match the property names). – Ant P May 05 '16 at 07:49
  • ok this is helping thank you for your concern :) – Arslan Afzal May 05 '16 at 08:28

1 Answers1

2

You should create a ViewModel for this, which wraps both Task and AssignedTask objects like this -

public class TaskViewModel
{
    public Task Task { get; set; }
    public AssignedTask AssignedTask { get; set; }
}

then bind your View with this view model i.e. TaskViewModel for example -

@model MyWebApplication2.Models.TaskViewModel

you will then be able to access the model properties just like any other object. For example to create a text box for TaskName, you could do -

@Html.TextBoxFor(m=>m.Task.TaskName)
Yogi
  • 9,174
  • 2
  • 46
  • 61