locked
Pass model into another model RRS feed

  • Question

  • User733430484 posted
      Sample Id R Acquisition Time QC Status Dataset File Method File P 213.617(cps) B 249.677(cps) Mg 285.213(cps) K 766.490(cps) P 213.617(mg/L) B 249.677(mg/L) Mg 285.213(mg/L) K 766.490(mg/L)
    1 BLANK STD R 20/4/2020 3:44:07 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 -199.0 4048.4 2084.1 49397.0 0.000 0.000 0.000 0.000
    2 S1 D R 20/4/2020 3:47:19 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 47608.8 64470.0 286558.3 312883.1 15.845 0.200 3.000 20.000
    3 S2 D R 20/4/2020 3:50:33 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 184798.9 234637.1 1431039.7 1225671.2 63.386 1.000 15.000 80.000
    4 S3 D R 20/4/2020 3:53:36 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 277093.8 341988.5 2820337.9 1882611.0 95.065 1.500 30.000 120.000
    5 S1 R 20/4/2020 3:56:43 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 466972.8 2932528.7 3192905.6 158.450 30.000 200.000
    6 S2 R 20/4/2020 3:59:46 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 2294537.5 13470784.5 12850322.6 10.000 150.000 800.000
    7 S3 R 20/4/2020 4:02:47 PM BKILANG 1161K_2020 NM 1 BKILANG 1161K_2020 2815178.6 3467674.2 26052236.2 19475828.9 950.650 15.000 300.000

    1200.000

    Table above from Excel.It succeed upload into ASP.NET MCV before I add a code to copy that to another model using "Loop".

    1. controller
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Step_Excel_2.Models;
    using System.IO;
    using System.Configuration;
    using System.Data.OleDb;
    using System.Data;
    
    namespace Step_Excel_2.Controllers
    {
        public class HomeController : Controller
        {
            [HttpGet]
            // GET: Home
            public ActionResult Index()
            {
                return View(new List<Mahkota>());
            }
            [HttpPost]
            public ActionResult Index(HttpPostedFileBase PostedFile)
            {
                List<Mahkota> Paksi_XY = new List<Mahkota>();
                if (PostedFile != null)
                {
                    string path = Server.MapPath("~/Test/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
    
                    string filepath = path + Path.GetFileName(PostedFile.FileName);
                    string extension = Path.GetExtension(PostedFile.FileName);
                    PostedFile.SaveAs(filepath);
    
                    string ConStr = string.Empty;
                    switch (extension)
                    {
                        case ".xls":
                            ConStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                            break;
                        case ".xlsx":
                            ConStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                            break;
                    }
                    ConStr = string.Format(ConStr, filepath);
    
                    OleDbConnection connExcel = new OleDbConnection(ConStr);
                    {
                        OleDbCommand cmdExcel = new OleDbCommand();
                        {
                            OleDbDataAdapter odaExcel = new OleDbDataAdapter();
                            {
                                DataTable dt = new DataTable();
                                cmdExcel.Connection = connExcel;
    
                                // Get Name first worksheet.
                                connExcel.Open();
                                DataTable dtExcelSchema;
                                dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                                string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                                connExcel.Close();
    
                                // Read data in Sheet.
                                connExcel.Open();
                                cmdExcel.CommandText = "SELECT * FROM [" + SheetName + "]";
                                odaExcel.SelectCommand = cmdExcel;
                                odaExcel.Fill(dt);
                                connExcel.Close();
    
    
                                ViewBag.header1 = dt.Columns[1].ColumnName.ToString().Replace("#", ".").Replace("_", "");
                                ViewBag.header7 = dt.Columns[7].ColumnName.ToString().Replace("#", ".").Replace("_", "");
                                ViewBag.header11 = dt.Columns[11].ColumnName.ToString().Replace("#", ".").Replace("_", "");
    
    
    
                                foreach (DataRow row in dt.Rows)
                                {
                                    var test = new Mahkota();
    
                                    {
                                        test.Sample_Id = row[1].ToString().Replace("#", ".");
                                    }
                                    // .
                                    if (String.IsNullOrEmpty(row[7].ToString()))
                                    {
                                        test.P_cps = Convert.ToDecimal(null);
                                    }
                                    else
                                    {
                                        test.P_cps = Convert.ToDecimal(row[7].ToString().Replace("#", "."));
                                    }
    
                                    // .
                                    if (String.IsNullOrEmpty(row[11].ToString()))
                                    {
                                        test.P_mgL = Convert.ToDecimal(null);
                                    }
                                    else
                                    {
                                        test.P_mgL = Convert.ToDecimal(row[11].ToString().Replace("#", "."));
                                    }
    
                                    var vm = new MahkotaVm();
                                    for (int i = 0; i < Paksi_XY.Count; i++)
                                    {
                                        vm.Mahkotas.Add(new Mahkota { P_cps = vm.Av_cps[i], P_mgL = vm.Av_mgL[i] });
                                    }
    
                                    Paksi_XY.Add(vm);
    
    
                                }
                            }
                        }
                    }
                }
                return View(Paksi_XY);
            }
        }
    }
    

    2. model

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Step_Excel_2.Models
    {
        public class Mahkota
        {
            public string Sample_Id { get; set; }
            public decimal P_cps { get; set; }
            public decimal P_mgL { get; set; }
        }
        public class MahkotaVm
        {
            public List<Mahkota> Mahkotas { get; set; }
    
            public decimal Av_cps { get; set; }
            public decimal Av_mgL { get; set; }
        }
    
    
    }

    3. view

    @model Step_Excel_2.Models.MahkotaVm
    
    <style>
        table {
            border-spacing: 10px;
            border-collapse: collapse;
        }
    
        table, th, tr, td {
            border: 1px solid black;
        }
    
        tr {
            height: 20px;
        }
    </style>
    
    @if (Model.Mahkotas.Count() > 0)
    {
        <div>
            @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <span>Select File:</span>
                <input type="file" name="postedFile" />
                <hr />
                <input type="submit" value="Upload" />
                <br />
            }
            <hr />
            <table>
                <tr>
                    <th>
                        @*@ViewBag.header1*@
                        Sample Id
                    </th>
                    <th>
                        @*@ViewBag.header11*@
                        P 213.617
                        (mg/L)
                    </th>
                    <th>
                        @*@ViewBag.header7*@
                        P 213.617
                        (cps)
                    </th>
    
                </tr>
    
                @foreach (var item in Model.Mahkotas)
                {
                    <tr>
                        <td>@item.Sample_Id</td>
                        <td>@item.P_mgL</td>
                        <td>@item.P_cps</td>
                    </tr>
                }
    
                <tr>
                    <td>@Model.Av_cps</td>
                    <td>@Model.Av_mgL</td>
                </tr>
    
            </table>
    
        </div>
    }

    What try to do is "How to show the result from var "test"  into var "vm" Using "Loop".

    The result may be like this

      Sample Id P 213.617(cps) P 213.617(mg/L)
    1 BLANK STD -199.0 0.000
    2 S1 D 47608.8 15.845
    3 S2 D 184798.9 63.386
    4 S3 D 277093.8 95.065
    5 S1 466972.8 158.450
    6 S2
    7 S3 2815178.6

    950.650

    P 213.617
    (cps)
    P 213.617
    (mg/L)
    -199.0 0.000
    47608.8 15.845
    184798.9 63.386
    277093.8 95.065
    466972.8 158.450
    2815178.6 950.650

    somebody can show the actual code can be.

    Sunday, November 15, 2020 3:52 AM

Answers

  • User1686398519 posted

    Hi sy_60, 

    1. vm.Av_cps = Paksi_XY[i].P_cps;
      1. At the end of the loop, the value of vm.Av_cps is the value of P_cps in the last set of data of Paksi_XY.
      2. In other words, the loop traverses every piece of data, but every time the subsequent data overwrites the existing value in vm.Av_cps.
      3. If you want to loop Paksi_XY to get P_cps and assign it to Av_cps, then you should modify your code like this:
        1. Model
          • public class MahkotaVm
            {
               public List<Mahkota> Mahkotas { get; set; }
               public List<decimal> Av_cpslist { get; set; }
               public List<decimal> Av_mgLlist { get; set; }
            }
        2. Controller
          • vm.Mahkotas = Paksi_XY;
            vm.Av_cpslist = new List<decimal>();
            vm.Av_mgLlist = new List<decimal>();
            for (int i = 0; i < Paksi_XY.Count; i++)
            {
                  vm.Av_cpslist.Add(Paksi_XY[i].P_cps);
                  vm.Av_mgLlist.Add(Paksi_XY[i].P_mgL);
            }
        3. Here is the result.:
    2. Note:
      1. I made a guess based on the name of "Av_cps": Do you want to get the average of all P_cps?
      2. If this is the case, there is no need to write a loop, you can write the code like this:
        • vm.Av_cps = Math.Round(Paksi_XY.Average(m => m.P_cps), 2);
          vm.Av_mgL = Math.Round(Paksi_XY.Average(m => m.P_mgL), 2);

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 20, 2020 8:40 AM
  • User1686398519 posted

    Hi sy_60, 

    You can modify it like this:

    @for (var i = 0; i < Model.Av_cpslist.Count; i++)
    {
     var item1 = Model.Av_cpslist[i];
     var item2 = Model.Av_mgLlist[i];
     <tr>
         <td>@item1</td>
         <td>@item2</td>
     </tr>
    }

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 23, 2020 7:54 AM

All replies

  • User1686398519 posted

    Hi sy_60, 

    According to your needs, I modified the code you provided, you can refer to it.

    Controller

            [HttpGet]
            // GET: Home
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Index(HttpPostedFileBase PostedFile)
            {
                var vm = new MahkotaVm();
                List<Mahkota> Paksi_XY = new List<Mahkota>();
                if (PostedFile != null)
                {
                    string path = Server.MapPath("~/Test/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string filepath = path + Path.GetFileName(PostedFile.FileName);
                    string extension = Path.GetExtension(PostedFile.FileName);
                    PostedFile.SaveAs(filepath);
                    string ConStr = string.Empty;
                    switch (extension)
                    {
                        case ".xls":
                            ConStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                            break;
                        case ".xlsx":
                            ConStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                            break;
                    }
                    ConStr = string.Format(ConStr, filepath);
                    OleDbConnection connExcel = new OleDbConnection(ConStr);
                    {
                        OleDbCommand cmdExcel = new OleDbCommand();
                        {
                            OleDbDataAdapter odaExcel = new OleDbDataAdapter();
                            {
                                DataTable dt = new DataTable();
                                cmdExcel.Connection = connExcel;
                                // Get Name first worksheet.
                                connExcel.Open();
                                DataTable dtExcelSchema;
                                dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                                string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                                connExcel.Close();
                                // Read data in Sheet.
                                connExcel.Open();
                                cmdExcel.CommandText = "SELECT * FROM [" + SheetName + "]";
                                odaExcel.SelectCommand = cmdExcel;
                                odaExcel.Fill(dt);
                                connExcel.Close();
                                ViewBag.header1 = dt.Columns[1].ColumnName.ToString().Replace("#", ".").Replace("_", "");
                                ViewBag.header7 = dt.Columns[7].ColumnName.ToString().Replace("#", ".").Replace("_", "");
                                ViewBag.header11 = dt.Columns[11].ColumnName.ToString().Replace("#", ".").Replace("_", "");
                                foreach (DataRow row in dt.Rows)
                                {
                                    var test = new Mahkota();
    
                                    {
                                        test.Sample_Id = row[1].ToString().Replace("#", ".");
                                    }
                                    // .
                                    if (String.IsNullOrEmpty(row[7].ToString()))
                                    {
                                        test.P_cps = Convert.ToDecimal(null);
                                    }
                                    else
                                    {
                                        test.P_cps = Convert.ToDecimal(row[7].ToString().Replace("#", "."));
                                    }
                                    // .
                                    if (String.IsNullOrEmpty(row[11].ToString()))
                                    {
                                        test.P_mgL = Convert.ToDecimal(null);
                                    }
                                    else
                                    {
                                        test.P_mgL = Convert.ToDecimal(row[11].ToString().Replace("#", "."));
                                    }
                                    Paksi_XY.Add(test);
                                }
                                vm.Mahkotas = Paksi_XY;
                            }
                        }
                    }
                }
                return View(vm);
            }

    View

    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <span>Select File:</span>
            <input type="file" name="postedFile" />
            <hr />
            <input type="submit" value="Upload" />
            <br />
        }
        <hr />
        @if (Model != null)
        {
            if (Model.Mahkotas.Count()>0)
            {
                <table>
                    <tr>
                        <th></th>
                        <th>
                            @*@ViewBag.header1*@
                            Sample Id
                        </th>
                        <th>
                            @*@ViewBag.header11*@
                            P 213.617
                            (mg/L)
                        </th>
                        <th>
                            @*@ViewBag.header7*@
                            P 213.617
                            (cps)
                        </th>
                    </tr>
                    @for (int i=0;i< Model.Mahkotas.Count();i++)
                    {
                        var item = Model.Mahkotas[i];
                        <tr>
                            <td>@(i+1)</td>
                            <td>@item.Sample_Id</td>
                            <td>@item.P_mgL</td>
                            <td>@item.P_cps</td>
                        </tr>
                    }
                </table>
                <br />
                <table>
                    <tr>
                        <th>
                            P 213.617
                            (cps)
                        </th>
                        <th>
                            P 213.617
                            (mg/L)
                        </th>
                    </tr>
                    @foreach (var item in Model.Mahkotas)
                    {
                    <tr>
                        <td>@item.P_cps</td>
                        <td>@item.P_mgL</td>
                    </tr>
                    }
                </table>
            }
        }
    </div>

    Here is the result. 

    Best Regards,

    YihuiSun

    Monday, November 16, 2020 6:25 AM
  • User733430484 posted

    Thank you YihuiSun .

    If I want the Loop method in Controller That how to do?.

    I test several code but not correctly true.

    This code bellow , Loop to the end not one by one.

                                    else
                                    {
                                        test.P_mgL = Convert.ToDecimal(row[11].ToString().Replace("#", "."));
                                    }
    
                                    Paksi_XY.Add(test);
    
                                }
    
                                vm.Mahkotas = Paksi_XY;
    
                                for (int i = 0; i < Paksi_XY.Count; i++)
                                {
                                    vm.Av_cps = Paksi_XY[i].P_cps;
                                    vm.Av_mgL = Paksi_XY[i].P_mgL;
                                }
    
                            }
                        }
                    }
                }
                return View(vm);
            }
        }
    }
    

    Friday, November 20, 2020 5:54 AM
  • User1686398519 posted

    Hi sy_60, 

    1. vm.Av_cps = Paksi_XY[i].P_cps;
      1. At the end of the loop, the value of vm.Av_cps is the value of P_cps in the last set of data of Paksi_XY.
      2. In other words, the loop traverses every piece of data, but every time the subsequent data overwrites the existing value in vm.Av_cps.
      3. If you want to loop Paksi_XY to get P_cps and assign it to Av_cps, then you should modify your code like this:
        1. Model
          • public class MahkotaVm
            {
               public List<Mahkota> Mahkotas { get; set; }
               public List<decimal> Av_cpslist { get; set; }
               public List<decimal> Av_mgLlist { get; set; }
            }
        2. Controller
          • vm.Mahkotas = Paksi_XY;
            vm.Av_cpslist = new List<decimal>();
            vm.Av_mgLlist = new List<decimal>();
            for (int i = 0; i < Paksi_XY.Count; i++)
            {
                  vm.Av_cpslist.Add(Paksi_XY[i].P_cps);
                  vm.Av_mgLlist.Add(Paksi_XY[i].P_mgL);
            }
        3. Here is the result.:
    2. Note:
      1. I made a guess based on the name of "Av_cps": Do you want to get the average of all P_cps?
      2. If this is the case, there is no need to write a loop, you can write the code like this:
        • vm.Av_cps = Math.Round(Paksi_XY.Average(m => m.P_cps), 2);
          vm.Av_mgL = Math.Round(Paksi_XY.Average(m => m.P_mgL), 2);

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 20, 2020 8:40 AM
  • User733430484 posted

    Thank very very much YihuiSun for your guide and explanation.It's useful.

    One more thing I need some advcie and if can how the code can be write.

    Why we still use this code;

    </table>
                <br />
                <table>
                    <tr>
                        <th>
                            P 213.617
                            (cps)
                        </th>
                        <th>
                            P 213.617
                            (mg/L)
                        </th>
                    </tr>
                    <tr>
                        @foreach (var item in Model.Mahkotas)
                        {
                        <tr>
                            <td>@item.P_mgL</td>
                            <td>@item.P_cps</td>
                        </tr>
                    }
                    </table>
            }
        }
    </div>

    and if I want use this code in view , How?

    </table>
                <br />
                <table>
                    <tr>
                        <th>
                            P 213.617
                            (cps)
                        </th>
                        <th>
                            P 213.617
                            (mg/L)
                        </th>
                    </tr>
                        <tr>
                            <td>@Model.Av_cpslist.ToString()</td>
                            <td>@Model.Av_mgLlist.ToString()</td>
                        </tr>
                </table>
            }
        }
    </div>

    Thank YuiShun for helping;

    Saturday, November 21, 2020 3:45 AM
  • User1686398519 posted

    Hi sy_60, 

    You can modify it like this:

    @for (var i = 0; i < Model.Av_cpslist.Count; i++)
    {
     var item1 = Model.Av_cpslist[i];
     var item2 = Model.Av_mgLlist[i];
     <tr>
         <td>@item1</td>
         <td>@item2</td>
     </tr>
    }

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 23, 2020 7:54 AM
  • User733430484 posted

    Thank you very much YihuiSun.

    Tuesday, November 24, 2020 7:26 AM