Home > Net >  how to pass the value to the viewModel from a multiple list
how to pass the value to the viewModel from a multiple list

Time:07-03

I have two model list and master model. I need to access and store value to the model properties. not sure how to do this using a viewModel? previously I was using viewData list and now I wan to test viewModel.

<---Model--->
public class Master
 {
   public List<Table1> T1 { get; set; }
   public List<Table2> T2 { get; set; }
 }
 
public class Table1
{
  public string sample1 { get; set; }
  public string sample1 { get; set; }
}

public class Table2
{
  public string sample1 { get; set; }
  public string sample2 { get; set; }
}


<--Controller-->
Master master  = new Master();
var getSamples = _db.dbSamples.Where(y => y.sample == "xxxx");

foreach(var row in T1)  <<---- I need help correcting this part. I believe this is not right...
  {
    foreach (var item in getSamples)
      {
        row.sample1 = item.A;
        row.sample2 = item.B;
      }
   }
return View(master);

CodePudding user response:

 public class Master
 {
   public List<Table1> T1 { get; set; }
   public List<Table2> T2 { get; set; }
 }
 
public class Table1
{
  public string sample1 { get; set; }
  public string sample2 { get; set; }
}

public class Table2
{
  public string sample1 { get; set; }
  public string sample2 { get; set; }
}

        <--Controller-->
        Master master  = new Master();
        var getSamples = _db.dbSamples.Where(y => y.sample == "sample1");
        var table1List = new List<Table1>();
        var table2List = new List<Table2>();
        var masterData= new Master();
            foreach (var item in getSamples)
              {
                var data = new Table1();
                data.A = item.A;
                data.B = item.B;
                table1List.add(data);
              }
        master.T1 = table1List;
        var getSamples1 = _db.dbSamples.Where(y => y.sample == "sample2");
           foreach (var item in getSamples1)
              {
                var data2 = new Table2();
                data2.A = item.A;
                data2.B = item.B;
                table2List.add(data2);
              }
        master.T2 = table2List;
        return View(master);

I assume that what you are trying to do is this. If it is not, please elaborate on the question.

Updated code. Change variable names accordingly.

  • Related