如何在mvc中动态显示模型的属性? [英] How to show the model's attribute dynamically in mvc?

查看:79
本文介绍了如何在mvc中动态显示模型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我可以显示和更新模型,如果我知道它的名称和值。例如,学生模型是这样的。

Now I can show and update a model if I know its name and value.For example,a studentmodel is like this.

public class student{
public string Name{ge;set}
public bool Sex{ge;set}
public bool Address{ge;set}
}
 @Html.TextBoxFor(model => model.Name)

 @Html.TextBoxFor(model => model.Sex)

 @Html.TextBoxFor(model => model.Address)



我想展示和更新模型,但我不知道有多少addAttribute和什么名字和va模型的lue?例如,如果我将一个Model返回给视图,模型是关于Fruit的,我想显示和更新它的属性,如price,Weight,如果我将一个Model返回给视图,模型是关于Student的,我想显示和更新他的属性,如姓名,性别和地址。


I want to show and update a model,but I do not know how many addAttribute and what name and value of the model?For example,If I return a Model to the view,the model is about Fruit,I want to show and update its attribute like price,Weight,If I return a Model to the view,the model is about Student,I want to show and update his attribute like name and sex and address.

推荐答案

创建两个部分视图,一个返回FruitModel的类型,其他类型为StudentModel并且在主视图中你不需要指定ViewModel类。在ActionResult中将ViewData或ViewBag中的状态设置为fruitModel或StudentModel。

Create two partial views one to return the type of FruitModel and other be the type of StudentModel and in the main view you no need to specify a ViewModel class.In the ActionResult set a status in ViewData or ViewBag as fruitModel or StudentModel.
public ActionResult Action()
{
if(it's studentModel)
   ViewData["Status"]=1
else
 ViewData["Status"]=2
return View();
}





之后从视图中可以返回基于viewData值的局部视图,如下所示。



After that from the view you can return the partial view based on the viewData value like below.

@if(Viewdata["Status"]==2)
Html.RenderPartial( "FirstPartialView")
else
Html.RenderPartial( "SecondPartialView")



希望这有助于


Hope this helps


这篇关于如何在mvc中动态显示模型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆