Reputation: 21
Requirement: I am suppose to develop an search widget which should generate the kendo controls based upon the model properties passed to the cshtml.
For example: If the model contains following properties such as
public string Name {get; set;}
then it should generate the textbox as a control, or if the property is
public string DateOfBirth {get; set;}
then it should generate a datePicker. What i was able to achieve is passing the model dynamically to the cshtml so that the cshtml would be loosely coupled. The issue i am facing is that the model which is getting passed has properties of different data types but in the cshtml are genetrated only with textbox controls for all the properties, which means that it is taking data type as string for all the properties of the model.
Please check the code below: Controller:
[HttpGet]
public ActionResult About(AddressModel obj)
{
dynamic model = obj;
return this.View(model);
}
cshtml:
@inherits BaseRazorView<object>
<h1>Search Criteria</h1>
@for (int i = 0; i < Model.GetType().GetProperties().Count(); i++)
{
<div class="row col-md-5">
@Html.EditorFor(model => model.GetType().GetProperties()[i].Name)
</div>
<br />
}
Upvotes: 2
Views: 912
Reputation: 3689
You can get the property type of the property by the propertyinfo and probably use it for differentiating the type of the input control you will use.
https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.propertytype(v=vs.110).aspx
For example
@for (int i = 0; i < Model.GetType().GetProperties().Count(); i++)
{
if(Model.GetProperties[i].PropertyType.Name == "String"){
// add an editor or a textbox
}
else if(Model.GetProperties[i].PropertyType.Name == "DateTime"){
// add a datetime picker
}
}
Upvotes: 2