Swagger - Is there a way to switch the example shown - swagger

The objects we are inserting are flexible because the user couldn't decide what parameters they wanted per item. This has made it interesting to ensure Swagger displays the information needed for the frontend developers. I am currently creating an "object" that has the example defined. The "object" is the same for every item with only the example changing. Is there a way to do a type of case statement for the example so I don't have to have several copies of the same object?
[HttpPost("getsources")]
[ProducesResponseType(typeof(SourceMaterialResponse), StatusCodes.Status200OK)]
public ActionResult GetSources([FromBody] FilterSourceInput filters)
{ .... }
public class SourceMaterialResponse
{
public bool success { get; set; }
public string message { get; set; }
/// <summary>
/// The array of Parameter Definitions in the format "Column Name" : "Value"
/// </summary>
/// <example>"Definition": "Source vendor name if commercially obtained"</example>
public List<Parameter_Definition> parameters { get; set; }
/// <summary>
/// The array of Sources in the format "Column Name" : "Value"
/// </summary>
/// <example> S{
/// "SourceID": "",
/// "MaterialID": "",
/// "Comments": "The most common form of Aluminum used in aircraft",
/// "CeramicOrGlassReinforced": "",
/// "CeramicOrGlassComposition": "",
/// "PlasticElastomer": "",
/// "MaterialDescription": "This is an aluminium alloy, with copper as the primary alloying element",
/// "PlasticComposition": "",
/// "OrganicPolymerCompositeCoreForm": "",
/// "NaturalType": "",
/// "OrganicPolymerCompositeMatrix": "",
/// "MaterialName": "Susan Alloy",
/// "MaterialClassOrType": "Metal",
/// "OrganicPolymerCompositeFiber": "",
/// "OrganicPolymerCompositeCore": "",
/// "MetalCompositionOrAlloy": "Copper"
/// }</example>
public List<Dictionary<string, string>> items { get; set; }
}

Related

Swashbuckle Description doesn't show up for properties with User Defined Types

Swashbuckle is not picking up the description while generating Swagger Json for properties with class types. It works fine with primitive data types.
for ex in below code, both of the definitions show up in xml file but only field with type string shows up with description in SwaggerJson. Field with type ServiceData is missing Description. This behavior is consistent all across the project:
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// Service Creation Request.
/// </summary>
public class ServiceCreationRequest
{
public ServiceCreationRequest(Servicedata serviceData, string name)
{
this.ServiceData = serviceData;
this.Name = name;
}
/// <summary>
/// Gets Service Data.
/// </summary>
public ServiceData ServiceData { get; set; }
/// <summary>
/// User Defined Service Name
/// </summary>
public string ServiceName{ get; set;}
}
}
snippet from xml file:
<member name="P:Service.ServiceCreationRequest.ServiceData ">
<summary>
Gets Service Data.
</summary>
</member>
<member name="P:Service.ServiceCreationRequest.Name">
<summary>
User Defined Service Name
</summary>
</member>
swagger json snippet:
"ServiceCreationRequest": {
"type": "object",
"properties": {
"serviceData": {
"$ref": "#/components/schemas/"
},
"name": {
"type": "string",
"description": "User Defined Service Name.",
"nullable": true,
"readOnly": true
},
"additionalProperties": false,
"description": "Service Creation Request."
}
Notice description missing for serviceData

adding a attributes to a custom html helper for drop down list

I have implemented the solution here:
http://www.spicelogic.com/Journal/ASP-NET-MVC-DropDownListFor-Html-Helper-Enum-5
It simply creates a dropdown list from member of enums. However, I want to associate a name with the dropdown list like here:
#Html.TextBox("username", Model.Username, new { id = "username" })
To illustrate, I want to use it in such a way:
#Html.DropDownListFor(m => m.FavoriteColor, new { id = "username" } )
How can I do that? How can I expand the Extention method of the EnumEditorHtmlHelper class?
Here is the definition of EnumEditorHtmlHelper:
namespace LojmanMVC.WebUI.Static
{
public static class EnumEditorHtmlHelper
{
/// <summary>
/// Creates the DropDown List (HTML Select Element) from LINQ
/// Expression where the expression returns an Enum type.
/// </summary>
/// <typeparam name="TModel">The type of the model.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="htmlHelper">The HTML helper.</param>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MvcHtmlString MyEnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
where TModel : class
{
TProperty value = htmlHelper.ViewData.Model == null
? default(TProperty)
: expression.Compile()(htmlHelper.ViewData.Model);
string selected = value == null ? String.Empty : value.ToString();
return htmlHelper.DropDownListFor(expression, createSelectList(expression.ReturnType, selected));
}
/// <summary>
/// Creates the select list.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="selectedItem">The selected item.</param>
/// <returns></returns>
private static IEnumerable<SelectListItem> createSelectList(Type enumType, string selectedItem)
{
return (from object item in Enum.GetValues(enumType)
let fi = enumType.GetField(item.ToString())
let attribute = fi.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault()
let title = attribute == null ? item.ToString() : ((DescriptionAttribute)attribute).Description
select new SelectListItem
{
Value = item.ToString(),
Text = title,
Selected = selectedItem == item.ToString()
}).ToList();
}
}
}
Thanks in advance.
You can do this using same method but it need second parameter to be a collection of SelectListItems and third parameter is for your custom attributes.
#Html.DropDownListFor(m => m.FavoriteColor, (IEnumerable<SelectListItem>)ViewBag.Colors, new {id="username" })

ASP.NET MVC 5 Showing 10 rows out of 500 records in Jquery Datatables With Server Side Processing

I Have a problem with my Jquery datatables. It shows only the first 10 rows out of 500 records in my database. Can someone help me to solve this problem.
Here is my code :
CONTROLLER :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using WinWin.Models;
namespace WinWin.Controllers
{
public class PostController : Controller
{
[Route("post")]
public ActionResult Index()
{
return View();
}
[Route("post/ajaxpost")]
public JsonResult ajaxpost(DTParameters param)
{
try
{
using (WintayoEntities db = new WintayoEntities())
{
var source = new List<Post>();
foreach (var p in db.ccp_post.ToList())
{
source.Add(new Post
{
id = p.post_id,
title = p.title,
date = p.post_on.ToString("yyyy-MM-dd"),
views = p.pageviews,
published = (p.is_published == 0) ? "Draft" : "Published",
featured = (p.is_featured == 0) ? "No" : "Yes",
action = string.Format(#"<i class=""fa fa-edit""></i> <i class=""fa fa-trash-o""></i>")
});
}
List<String> columnSearch = new List<String>();
foreach (var col in param.Columns)
{
columnSearch.Add(col.Search.Value);
}
List<Post> data = new ResultPost().GetResult(param.Search.Value, param.SortOrder, param.Start, param.Length, source, columnSearch);
int count = new ResultPost().Count(param.Search.Value, data, columnSearch);
DTResult<Post> result = new DTResult<Post>
{
draw = param.Draw,
data = data,
recordsFiltered = count,
recordsTotal = count
};
return Json(result);
}
}
catch (Exception e)
{
return Json(new { error = e.Message });
}
}
}
}
DATATABLE VIEW MODEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WinWin.Models
{
/// <summary>
/// A full result, as understood by jQuery DataTables.
/// </summary>
/// <typeparam name="T">The data type of each row.</typeparam>
public class DTResult<T>
{
/// <summary>
/// The draw counter that this object is a response to - from the draw parameter sent as part of the data request.
/// Note that it is strongly recommended for security reasons that you cast this parameter to an integer, rather than simply echoing back to the client what it sent in the draw parameter, in order to prevent Cross Site Scripting (XSS) attacks.
/// </summary>
public int draw { get; set; }
/// <summary>
/// Total records, before filtering (i.e. the total number of records in the database)
/// </summary>
public int recordsTotal { get; set; }
/// <summary>
/// Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data).
/// </summary>
public int recordsFiltered { get; set; }
/// <summary>
/// The data to be displayed in the table.
/// This is an array of data source objects, one for each row, which will be used by DataTables.
/// Note that this parameter's name can be changed using the ajaxDT option's dataSrc property.
/// </summary>
public List<T> data { get; set; }
}
/// <summary>
/// The additional columns that you can send to jQuery DataTables for automatic processing.
/// </summary>
public abstract class DTRow
{
/// <summary>
/// Set the ID property of the dt-tag tr node to this value
/// </summary>
public virtual string DT_RowId
{
get { return null; }
}
/// <summary>
/// Add this class to the dt-tag tr node
/// </summary>
public virtual string DT_RowClass
{
get { return null; }
}
/// <summary>
/// Add this data property to the row's dt-tag tr node allowing abstract data to be added to the node, using the HTML5 data-* attributes.
/// This uses the jQuery data() method to set the data, which can also then be used for later retrieval (for example on a click event).
/// </summary>
public virtual object DT_RowData
{
get { return null; }
}
}
/// <summary>
/// The parameters sent by jQuery DataTables in AJAX queries.
/// </summary>
public class DTParameters
{
/// <summary>
/// Draw counter.
/// This is used by DataTables to ensure that the Ajax returns from server-side processing requests are drawn in sequence by DataTables (Ajax requests are asynchronous and thus can return out of sequence).
/// This is used as part of the draw return parameter (see below).
/// </summary>
public int Draw { get; set; }
/// <summary>
/// An array defining all columns in the table.
/// </summary>
public DTColumn[] Columns { get; set; }
/// <summary>
/// An array defining how many columns are being ordering upon - i.e. if the array length is 1, then a single column sort is being performed, otherwise a multi-column sort is being performed.
/// </summary>
public DTOrder[] Order { get; set; }
/// <summary>
/// Paging first record indicator.
/// This is the start point in the current data set (0 index based - i.e. 0 is the first record).
/// </summary>
public int Start { get; set; }
/// <summary>
/// Number of records that the table can display in the current draw.
/// It is expected that the number of records returned will be equal to this number, unless the server has fewer records to return.
/// Note that this can be -1 to indicate that all records should be returned (although that negates any benefits of server-side processing!)
/// </summary>
public int Length { get; set; }
/// <summary>
/// Global search value. To be applied to all columns which have searchable as true.
/// </summary>
public DTSearch Search { get; set; }
/// <summary>
/// Custom column that is used to further sort on the first Order column.
/// </summary>
public string SortOrder
{
get
{
return Columns != null && Order != null && Order.Length > 0
? (Columns[Order[0].Column].Data + (Order[0].Dir == DTOrderDir.DESC ? " " + Order[0].Dir : string.Empty))
: null;
}
}
}
/// <summary>
/// A jQuery DataTables column.
/// </summary>
public class DTColumn
{
/// <summary>
/// Column's data source, as defined by columns.data.
/// </summary>
public string Data { get; set; }
/// <summary>
/// Column's name, as defined by columns.name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Flag to indicate if this column is searchable (true) or not (false). This is controlled by columns.searchable.
/// </summary>
public bool Searchable { get; set; }
/// <summary>
/// Flag to indicate if this column is orderable (true) or not (false). This is controlled by columns.orderable.
/// </summary>
public bool Orderable { get; set; }
/// <summary>
/// Specific search value.
/// </summary>
public DTSearch Search { get; set; }
}
/// <summary>
/// An order, as sent by jQuery DataTables when doing AJAX queries.
/// </summary>
public class DTOrder
{
/// <summary>
/// Column to which ordering should be applied.
/// This is an index reference to the columns array of information that is also submitted to the server.
/// </summary>
public int Column { get; set; }
/// <summary>
/// Ordering direction for this column.
/// It will be dt-string asc or dt-string desc to indicate ascending ordering or descending ordering, respectively.
/// </summary>
public DTOrderDir Dir { get; set; }
}
/// <summary>
/// Sort orders of jQuery DataTables.
/// </summary>
public enum DTOrderDir
{
ASC,
DESC
}
/// <summary>
/// A search, as sent by jQuery DataTables when doing AJAX queries.
/// </summary>
public class DTSearch
{
/// <summary>
/// Global search value. To be applied to all columns which have searchable as true.
/// </summary>
public string Value { get; set; }
/// <summary>
/// true if the global filter should be treated as a regular expression for advanced searching, false otherwise.
/// Note that normally server-side processing scripts will not perform regular expression searching for performance reasons on large data sets, but it is technically possible and at the discretion of your script.
/// </summary>
public bool Regex { get; set; }
}
}
VIEW
<div class="contentpanel">
<div class="panel panel-default">
<div class="panel-body">
<div class="table-responsive">
<table class="table mb30 table-class-ajax" data-list="post/ajaxpost">
<colgroup>
<col style="width: 4%;" />
<col style="width: auto;" />
<col style="width: 13%;" />
<col style="width: 9%;" />
<col style="width: 8%;" />
<col style="width: 8%;" />
<col style="width: 105px;" />
</colgroup>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publish Date</th>
<th>Pageviews</th>
<th>Featured</th>
<th>Published</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div><!-- contentpanel -->
<script>
$(document).ready(function () {
var oTable = $(".table-class-ajax").DataTable({
"serverSide": true,
"ajax": {
"type": "POST",
"url": "post/ajaxpost",
"contentType": 'application/json; charset=utf-8',
'data': function (data) { return data = JSON.stringify(data); }
},
"processing": true,
"paging": true,
"pagingType": "full_numbers",
"deferRender": true,
"columns": [
{ "data": "id" },
{ "data": "title" },
{ "data": "date" },
{ "data": "views" },
{ "data": "featured" },
{ "data": "published" },
{ "data": "action" }
],
"order": [0, "asc"],
"info": true,
});
});
</script>
You got paging turned on in your client side script for your DataTable.
//...
"paging": false
//...
In Your code if you see Datatable view model the lenth parameter states the total coloumns to be loaded for the data table.
/// <summary>
/// Number of records that the table can display in the current draw.
/// It is expected that the number of records returned will be equal to this number, unless the server has fewer records to return.
/// Note that this can b**e -1 to** indicate that all records should be returned (although that negates any benefits of server-side processing!)
/// </summary>
public int **Length** { get; set; }
Set the value to -1 as said in the code

Dynatree with ASP.NET MVC

Has anybody got any examples of using the Dynatree plugin with MVC? I have been wrestling with it without much progress. I have an action method which returns a JsonResult (but selects all columns in the underlying table, not sure if this is the problem) and in my initajax call , all I'm doing is calling this method.
If it's not too much trouble, I am looking for sample View and Controller action methods.
Thanks in advance for any help
You need to create an object to serialize the nodes eg.
public interface ITreeItem
{
}
/// <summary>
/// Tree Item Leaf.
/// </summary>
public class TreeItemLeaf :ITreeItem
{
/// <summary>
/// Gets the Title.
/// </summary>
public string title;
/// <summary>
/// Gets the Tooltip.
/// </summary>
public string tooltip;
/// <summary>
/// Gets the key.
/// </summary>
public string key;
/// <summary>
/// Gets the Data.
/// </summary>
public string addClass;
/// <summary>
/// Gets the Children.
/// </summary>
public IList<ITreeItem> children;
/// <summary>
/// Gets the rel attr.
/// </summary>
public string rel;
/// <summary>
/// Gets the State.
/// </summary>
public bool isFolder;
/// <summary>
/// Gets the State.
/// </summary>
public bool isLazy;
/// <summary>
/// Initializes a new instance of the <see cref="TreeItemLeaf"/> class.
/// </summary>
public TreeItemLeaf()
{
children = new List<ITreeItem>();
}
/// <summary>
/// Initializes a new instance of the <see cref="TreeItemLeaf"/> class.
/// </summary>
/// <param name="type">The type of node.</param>
/// <param name="id">The Id of the node.</param>
/// <param name="title">The Title of the node.</param>
/// <param name="tooltip">The Tooltip of the node.</param>
public TreeItemLeaf(String type, Guid id, String title, String tooltip)
{
key = id.ToString();
this.title = title;
isFolder = false;
isLazy = false;
this.tooltip = tooltip;
children = new List<ITreeItem>();
}
}
/// <summary>
/// Tree Item.
/// </summary>
public class TreeItem : TreeItemLeaf
{
/// <summary>
/// Gets the State.
/// </summary>
public new bool isFolder;
/// <summary>
/// Initializes a new instance of the <see cref="TreeItem"/> class.
/// </summary>
public TreeItem() : base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TreeItem"/> class.
/// </summary>
/// <param name="type">The type of node.</param>
/// <param name="id">The Id of the node.</param>
/// <param name="title">The Title of the node.</param>
/// <param name="tooltip">The tooltip of the node.</param>
public TreeItem(String type, Guid id, String title, String tooltip) : base(type, id, title, tooltip)
{
isFolder = true;
isLazy = true;
}
}
Once you have this, you can return a Json(IList<ITreeItem>) which you will need to build up from your results..
If you go to the Dynatee demo http://wwwendt.de/tech/dynatree/doc/samples.html , you can use Firefox/Firebug to study the HTTP requests to see exactly what is being passed in and returned.
My tree in the view is as follows :
// --- Initialize first Dynatree -------------------------------------------
$("#tree").dynatree({
fx: { height: "toggle", duration: 500 },
selectMode: 1,
clickFolderMode: 1,
children : #Html.Raw(String.Format("{0}", ViewData["tree"]).Replace("\"children\":[],", "")),
onLazyRead: function (node) {
node.appendAjax({
url: "#Url.Action("treedata", "tree")",
type: "GET",
data: { "id": node.data.key, // Optional url arguments
"mode": "all"
},
error: function(node, XMLHttpRequest, textStatus, errorThrown) {
}
}
});
}, //.... cut short for brevity
I am embeding the initial tree state in the "children:" part. And the Ajax reading is being set up in the "onLazyRead:" part.
My Ajax call is:
public JsonResult TreeData(FormCollection form)
{
return GetTreeData(Request.QueryString["id"], Request.QueryString["uitype"]);
}
The GetTreeData() function returns Json(ITreeItem);
I would recommend you use Firefox/Firebug and its "NET" function to see what is going and coming back.
Hope that helps.
I've just found Dynatree and I'm using it on my MVC project. Here's an example of how I did it. I decided to just put the data directly in the View like the basic example.
My data is a list of cities within California, grouped by county.
My controller simply passes a view model to my View and the view model has a CitiesAvailable property:
public IEnumerable<City> CitiesAvailable { get; set; }
My list of City objects is grabbed from the database (EF4) and the actual City object is the following:
In my View I create a ul containing the list of counties and their cities (I'm using Razor but webforms should be easy enough to figure out):
<div id="tree">
<ul id="treedata" style="display: none;">
#foreach (var county in Model.CitiesAvailable.Select(c => c.County).Distinct().OrderBy(c => c))
{
<li data="icon: 'false'">#county
<ul>
#foreach (var city in Model.CitiesAvailable.Where(c => c.County == county).OrderBy(c => c.Name))
{
<li data="icon: 'false'" id="#city.Id">#city.Name</li>
}
</ul>
</li>
}
</ul>
</div>
Then in my JavaScript I use the following:
$("#tree").dynatree({
checkbox: true,
selectMode: 3,
fx: { height: "toggle", duration: 200 }
});
It works great! Here's a sample of the output with a few items checked:
Let me know if anything doesn't make sense.
Note, I use data="icon: 'false'" in my li elements because I don't want the icons.
You can simply convert the object to json string, and send it to server as text
this is the js code:
var dict = $("#tree").dynatree("getTree").toDict();
var postData = JSON.stringify(dict["children"]);
$.ajax({ type: "POST",
url: "/UpdateServer/SaveUserTree",
data: {tree:postData},
dataType: "html"
});
And this is the controller code:
[HttpPost]
public void SaveUserTree(string tree = "")
{
HttpContext.Application["UserTree"] = tree;
}
You can send this string data back to client
if (HttpContext.Application["UserTree"] != null)
ViewBag.TreeData = new HtmlString(HttpContext.Application["UserTree"].ToString());
And finally, you can initial the tree, in the View with this data:
var treeData= #(ViewBag.TreeData)
$(function(){
// --- Initialize sample trees
$("#tree").dynatree({
children: treeData
});
});

ASP.NET MVC: creating controls dynamically

This is the control builder class...
public class ControlBuilder
{
/// <summary>
/// Html Control class for controlbuilder Control .
/// </summary>
protected HTMLControl formControl;
/// <summary>
/// Html Control class for the label.
/// </summary>
private HTMLControl labelControl;
/// <summary>
/// Getting the property for the Control .
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
public HTMLControl Form
{
get { return formControl; }
}
/// <summary>
/// Creating a label for the Control.
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
public HTMLControl Label
{
get { return labelControl; }
}
/// <summary>
/// Creating a construtor for the controlbuilder taking in Zero
/// arguments it creates a labl for the Control .
/// </summary>
/// <history>
/// [LuckyR] 13/8/2009 Created
/// </history>
public ControlBuilder() { }
/// <summary>
/// A construtor for the controlbuilder which
/// creates a label for the Control .
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
public ControlBuilder(string labelName)
{
Label label = new Label();
label.Text = labelName;
label.Width= 200;
labelControl = new HTMLControl(label);
}
/// <summary>
/// Control build property that is used to biuld the Html
/// markup for the created Control.
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
public string BuildControl()
{
this.CreateControl();
this.SetAttribute();
return this.RenderHTML();
}
/// <summary>
/// Render Html tags for the Control with label .
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
public string RenderHTML()
{
return labelControl.RenderHTML() + ": " + formControl.RenderHTML();
}
/// <summary>
/// Used to Set Attributes for the Control .
/// </summary>
/// <history>
/// [LuckyR] 13/8/2009 Created
/// </history>
protected virtual void SetAttribute() { }
/// <summary>
/// Used to create the Control .
/// </summary>
/// <history>
/// [LuckyR] 13/8/2009 Created
/// </history>
protected virtual void CreateControl() { }
/// <summary>
/// A list of all the Controls that will be created during the
/// program run .
/// </summary>
private IList<ControlBuilder> Controls = new List<ControlBuilder>();
/// <summary>
/// A property to add Control to the ControlBuilder that are created by
/// the user.
/// </summary>
/// <history>
/// [LuckyR] 13/8/2009 Created
/// </history>
/// <param name="Control">Controls from the controlbuilder class</param>
public void AddControl(ControlBuilder Control)
{
Controls.Add(Control);
}
/// <summary>
/// A property to display the Controls that are created by
/// the user.
/// </summary>
/// <history>
/// [LuckyR] 13/8/2009 Created
/// </history>
public string Display()
{
string Html = string.Empty;
foreach (ControlBuilder builder in Controls)
{
Html += builder.BuildControl();
Html += "<br /><br />";
}
return Html;
}
}
}
this is how i build a control
public class TextBoxBuilder : ControlBuilder
{
/// <summary>
/// Creating a web Control textBox.
/// </summary>
private TextBox textBox;
/// <summary>
/// Creating an Id to add as an attribute .
/// </summary>
private string Id;
/// <summary>
/// Creating an Value to add as an attribute .
/// </summary>
private string Value;
/// <summary>
/// Creating a Textbox constructor which takes in LabelName and Id.
/// to create a label for the Control.
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
public TextBoxBuilder(string labelName, string id , string value): base(labelName)
{
this.Id = id;
this.textBox = new TextBox();
this.Value = value;
}
/// <summary>
/// Used to Set properties for the Control .
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
protected override void SetAttribute()
{
this.textBox.ID = this.Id;
this.textBox.Text = this.Value;
}
/// <summary>
/// Used to create the Control . That is done by calling the HtmlControl class
/// which inturn renders the particular Control for us .
/// </summary>
/// <history>
/// [LuckyR] 10/8/2009 Created
/// </history>
protected override void CreateControl()
{
this.formControl = new HTMLControl(this.textBox);
}
}
}
In my home controller i did this ...
public ActionResult Create()
{
///Where i am contacting the linq to sql classs for performing ths operagtion
foreach (var control in Rep.GetData(ScreenName))
{
string Type = control.Type;
string value = null;
if (id != Guid.Empty)
{
value = DataObj.GetValue(control.TableName, control.ControlName, id);
}
switch (Type)
{
case ("TextBox"):
/// Buliding a textBox box
controlbuilder.AddControl(new TextBoxBuilder(control.Field, control.ControlName, value));
break;
case ("CheckBox"):
/// Bulidig a CheckBox .
controlbuilder.AddControl(new CheckBoxBuilder(control.Field, control.ControlName , value));
break;
case ("DatePicker"):
/// Bulidig a DatePicker .
controlbuilder.AddControl(new DatePicker(control.Field, control.ControlName, value));
break;
case ("DropDownList"):
///Building a dropdownlist.
List<string> list = DataObj.GetDropDownValues(control.Id);
controlbuilder.AddControl(new DropDownListBuilder(control.Field, control.ControlName, list,value));
break;
case ("TextArea"):
/// Building a textBox area .
controlbuilder.AddControl(new TextArea(control.Field, control.ControlName , value));
break;
default:
break;
}
}
return View(controlbuilder);
}
The view page looks like this ...
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Fields</legend>
<p>
<%= ViewData.Model.Display() %>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index")%>
</div>
since i am passing my class into the view i can retrieve all the data there with .display .
There is no concept of controls in ASP.NET MVC any longer.
You have two options:
When the user clicks a button, you handle this POST request in a controller action, set some sort of flag in your view model to now show a textbox, then return the same view which in its turn will look at the flag and generate a text box if required. This will incur a complete round-trip which will be somewhat similar to the postback in WebForms.
You do it in-place with JavaScript. You intercept a click event on a button and you inject an input/textarea HTML element into your document structure.

Resources