【问题标题】:ASP.NET C# Dictionary inside a class is received empty when passed to another function传递给另一个函数时,类中的 ASP.NET C# 字典接收为空
【发布时间】:2021-01-05 12:59:32
【问题描述】:

我确定这是一个相当新手的问题,但我没有看到其他有用的帖子,所以请提供一些帮助。

我在一个类中有一个字典,当我创建一个新对象并将其传递给另一个 ASP.NET 函数时,除了没有元素的字典之外,该类得到了正确的通知。

请问,我错过了什么??

这是课

    public class Reparto
    {
        [BindProperty]
        public string ID { get; set; }
        public Dictionary<string, string> LecturaSalida { get; set; }
        [BindProperty]
        [Display(Name = "Lectura")]
        public string Lectura { get; set; }
        [BindProperty]
        public string JsonDictionary { get; set; }

        public Reparto()
        {
            //MVC asks for this
        }

        public Reparto(string ID, Dictionary<string, string> LecturaSalida)
        {
            this.ID = ID;
            this.LecturaSalida = new Dictionary<string, string>(LecturaSalida);
            this.JsonDictionary = JsonSerializer.Serialize(LecturaSalida); // test to confirm dict is received
        }
    }

这是asp控制器代码(简化)

       [HttpPost]
        public IActionResult Index(string ID)
        {
            try
            {
                Reparto DatosReparto = new Reparto(ID, Context.ObtenerReparto(ID));  // This populates DatosReparto object correctly
                return RedirectToAction("Reparto", DatosReparto);                    // And goes to the next point 
            }
            catch 
            {
                ModelState.AddModelError("ID", "Invalid!");
            }
            return View();
        }


        public IActionResult Reparto(Reparto DatosReparto) 
        {
            int test = DatosReparto.LecturaSalida.Count; // zero elements!!! while the other properties are correctly informed, as JsonDict which is correctly informed 4ex.

            return View();
        }

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc


    【解决方案1】:

    而不是:

    return RedirectToAction("Reparto", DatosReparto);  
    

    呼叫:

    return Reparto(DatosReparto);  
    

    【讨论】:

    • 但在这种情况下,如果我不使用 RedirectToAction,它会保留在 Index Action 中。我可以返回 View("Reparto") 来更改视图,但是当它提交时会再次执行索引操作。
    • 试试吧。我总是使用这种语法。不管它留在哪里,它都会产生与 RedirectToAction 相同的结果。它将从 Reparto 返回视图和模型。如果它有例如一些代码并返回 View("Reparto", DatosReparto) 它将返回完全不同的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2018-08-20
    • 2018-08-02
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    相关资源
    最近更新 更多