美文网首页
Html.Partial传递model和ViewDataDict

Html.Partial传递model和ViewDataDict

作者: 漫漫江雪 | 来源:发表于2017-09-15 16:05 被阅读0次

    Html.Partial也可以传递多个数据
    形如:@Html.Partial("Test", Model, new ViewDataDictionary { { "key", "object value" } });
    1、contorller方法

    public async Task<ActionResult> Create(string majorId="")
            {
                //取选择的专业
                var major = await _majorService.GetByIdAsync(majorId);
                ViewBag.Major = major;
                var nowYear = DateTime.Now.Year;
                List<SelectListItem> gradeList = new List<SelectListItem>();
                for (int i = -3; i <= 3; i++)
                {
                    string grade = (nowYear + i).ToString();
                    gradeList.Add(new SelectListItem(){Text=grade,Value=grade,Selected = (i==0)});
                }
                gradeList.Insert(0, new SelectListItem() { Text = "--请选择--",Value="",Selected = false});
                ViewBag.GradeList = gradeList;
                var model = new ClassInfoModel(){ MajorId = majorId };
                return View(model);
            }
    

    2、视图

    @model xxxxxx.ClassInfoModel
    
    @{
        ViewBag.Title = "新增";
        Layout = "~/Views/Shared/_Layout.cshtml";
        var major = ViewBag.Major as MajorModel ?? new MajorModel();
        var gradeList = ViewBag.GradeList as List<SelectListItem> ?? new List<SelectListItem>();
    }
    
    @using (Html.BeginForm("Create", "ClassInfo", FormMethod.Post, new { @class = "cssClass" }))
    {
        @Html.Partial("_CreateOrUpdate", Model, new ViewDataDictionary() { { "majorName", major.Name },{"gradeList",gradeList} })
    }
    

    3、在_CreateOrUpdate分部视图中使用数据

    @model xxxxxx.ClassInfoModel
    
    专业:@ViewData["majorName"].ToString()
    年级:@Html.DropDownList("Grade", ViewData["gradeList"] as IEnumerable<SelectListItem>, new
                    {
                        @class = "form-control",
                        data_required = "true"
                    })
    

    4、Html.RenderAction传递多个方法参数值

    <div class="ccccc" id="publicView">
                                    @{
                                        Html.RenderAction("actionName", "controllerName", new { CourseId = course.Id, TermId = term.Id });
                                    }
                                </div>
    

    相关文章

      网友评论

          本文标题:Html.Partial传递model和ViewDataDict

          本文链接:https://www.haomeiwen.com/subject/baassxtx.html