ASP.NET Dynamic form generation and submition - c#

I need to create a form where for each day in the month the user will enter in several different values (Im thinking a grid sort of thing, values along the top, day of the month along the side) using ASP.NET forms with C# backend...
So what would be the best way to generate this form? I dont want to hardcode that many controls as it would make the submition a little annoying but i also would need to be able to give it values entered in previous days and have it display them in the textboxes.
How would i go about creating this form and also how would i get the values from the textboxes in the backend?

Here is an example application that creates a dynamic form and submits it back to the database. It's written in VB.Net but im sure it's easily converted to C#.
http://www.asp101.com/samples/form_dynamic_aspx.asp
Basically the way it works is adding the controls to the form dynamically then accessing the values that are posted to the server with the Request.Form collection.

If you're building from scratch and can use the ASP.NET MVC framework, might be worth checking out the Dynamic Forms project over at codeplex: http://mvcdynamicforms.codeplex.com/
It might be overkill for your situation, but this appears a pretty powerful way to have a dynamic forms approach (you can store the config in an XML file, in a database etc), and posting the data back is handled by evaluating the Request object in server side code.

You can do this very easily using my FormFactory library.
By default it reflects against a view model to produce a PropertyVm[] array:
```
var vm = new MyFormViewModel
{
OperatingSystem = "IOS",
OperatingSystem_choices = new[]{"IOS", "Android",};
};
Html.PropertiesFor(vm).Render(Html);
```
but you can also create the properties programatically, so you could load settings from a database then create PropertyVm.
This is a snippet from a Linqpad script.
```
//import-package FormFactory
//import-package FormFactory.RazorGenerator
void Main()
{
var properties = new[]{
new PropertyVm(typeof(string), "username"){
DisplayName = "Username",
NotOptional = true,
},
new PropertyVm(typeof(string), "password"){
DisplayName = "Password",
NotOptional = true,
GetCustomAttributes = () => new object[]{ new DataTypeAttribute(DataType.Password) }
}
};
var html = FormFactory.RazorEngine.PropertyRenderExtension.Render(properties, new FormFactory.RazorEngine.RazorTemplateHtmlHelper());
Util.RawHtml(html.ToEncodedString()).Dump(); //Renders html for a username and password field.
}
```
Theres a demo site with examples of the various features you can set up (e.g. nested collections, autocomplete, datepickers etc.)

Related

How do I show a loading screen/icon while loading a view that requires querying a database? Asp.Net Core C#

Currently I have a view that has just a single form with three values. When a user submits the form with those three values, my controller checks if all three values actually have a value other than being empty, and if they do then it calls my service that fetches data.
public IActionResult Index(string clientName = "", string tableName = "", string date = "")
{
if (!string.IsNullOrEmpty(clientName) && !string.IsNullOrEmpty(tableName) && !string.IsNullOrEmpty(date))
{
// Unimportant stuff for setting temp variables for FetchData parameters removed
TheData = _fieldDataService.FetchData(tempAcr, tempID, tableName, date, numRows);
}
return View(TheData);
}
My goal is to make the view display a loading icon or something while the data is being fetched. I've looked into JQuery and Ajax but I have no experience with either and cannot figure out how to apply them to my specific task. Since I am using Asp.Net Core, I also looked into using Blazor, but I couldn't wrap my head around it either.
Could somebody point me in the right direction as to what I should/could use to solve this problem? I have a vague understanding that there needs to be some sort of asynchronous function that retrieves the data, but nothing more than that.
You need to fetch the data with JavaScript and manipulate the UI to show a loader. But anyway, a request like this should be so fast, that you don't even need a loader.
I'm also a bit worried that you are passing a tableName as input parameter. You aren't just string concatenating the query right? You might be susceptible to SQL injections, see https://en.wikipedia.org/wiki/SQL_injection.
To do a request with JavaScript, look into the XMLHttpRequest, see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest, or the new way of doing it with fetch(...), see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
This answer shows a more practical example: Display loading image while ajax fetches file content.

fill asp dropdown list with SQL records by using kentico API calls

okay, it seems that no one is explaining the process of this issue completely, even kentico's documentations are not well organized and clear. My problem is that i have more than 50 records in a table in SQL which i would like to load in a single ASP dropdown list (because it would be a bad practice to fill it statically), and I am new to kentico so my problem is that I need a complete explanation about the process from A to Z, from building the query in kentico, to using it in visual. please post some examples if possible.
also please note that i have seen many examples like this one:
https://docs.kentico.com/k10/custom-development/developing-web-parts/advanced-web-part-development-scenarios/developing-custom-filters
but these examples are showing us only the last step, which is using DepartmentInfoProvider.GetDepartments(); to fill the dropdownlist, my main focus is to know how and where and using what they created the DepartmentInfoProvider class on the first place.
you should read about creating custom modules. There is a section how to add a class to the module. As soon as you add a class to the module, you'll be able to generate its Info and InfoProvider class, then add these files to solution and use them.
Farah, Another person asked a similar question:
https://devnet.kentico.com/questions/custom-filter-with-a-drop-down-list-from-the-databse
This will help give a little info on the Info and InfoProviders in Kentico
To be more specific to your needs though, you can use the QueryInfoProvider.ExecuteQuery to use a custom Kentico query that selects from your table, OR you can as Anton suggested make a custom module, but if you're new to Kentico this may be a bit much for you.
Lastly, if you want i have a universal filter webpart (just haven't published it yet) which gives you the ability to simply write a SQL query and then define how that selected value affects your repeater (you design the WHERE condition). Just tell me if you want it.
The solution was far more simple than I thought, First we should create a Query in Page Type --> Queries --> new Query --> specify queryName and queryText, the query gets the data from database, second in visual we have to write:
using System.Data;
private void initializeDropDownList(String queryName, String rowName, DropDownList dd)
{
List<String> listData = new List<String>();
DataSet dataset = new DataQuery("custom.PageType." + queryName).Execute();
foreach (DataRow row in dataset.Tables[0].Rows)
{
listData.Add(row[rowName].ToString());
}
String[] arrayData = listData.ToArray();
foreach (String data in arrayData)
{
if (data.Equals("")) { continue; }
else
{
dd.Items.Add(new ListItem(data));
}
}
}

Finding HTML elements by 'id' inside a coded UI test in Visual Studio using C#?

So I have a very simple Coded UI Test in Visual Studio 13' that simply visits my web page, logs in, and then clicks on a menu item that directs it to a table. During different times, that table may be empty or may be full of data. All I want to do is simply grab the 'id' attribute of the table and make assertions about its row count. Using C#, what is the easiest way to do this? I've researched and it looks like HtmlControl(s) are a possible solution (like the example here) but I can't seem to get the result I want. Thanks!
You can use this:
public HtmlEdit TbxUserName
{
get
{
if ((tbxUserName == null))
{
tbxUserName = new HtmlEdit(browser);
tbxUserName.SearchProperties[HtmlControl.PropertyNames.Id] = "UserName";
}
return tbxUserName;
}
}
There can by problem in webforms if you have generated ids, but it can be done with 'contains':
divMarketMap.SearchProperties.Add(new PropertyExpression(HtmlControl.PropertyNames.Id, "someId", PropertyExpressionOperator.Contains));

Can I pass a .net Object via querystring?

I stucked at a condition , where i need to share values between the pages. I want to share value from Codebehind via little or no javascript. I already have a question here on SO , but using JS. Still did'nt got any result so another approach i am asking.
So I want to know can i pass any .net object in query string. SO that i can unbox it on other end conveniently.
Update
Or is there any JavaScript approach, by passing it to windows modal dialog. or something like that.
What I am doing
What i was doing is that on my parent page load. I am extracting the properties from my class that has values fetched from db. and put it in a Session["mySession"]. Some thing like this.
Session["mySession"] = myClass.myStatus which is List<int>;
Now on one my event that checkbox click event from client side, i am opening a popup. and on its page load, extracting the list and filling the checkbox list on the child page.
Now from here user can modify its selection and close this page. Close is done via a button called save , on which i am iterating through the checked items and again sending it in Session["mySession"].
But the problem is here , when ever i again click on radio button to view the updated values , it displays the previous one. That is , If my total count of list is 3 from the db, and after modification it is 1. After reopening it still displays 3 instead of 1.
Yes, you could but you would have to serialize that value so that it could be encoded as a string. I think a much better approach would be to put the object in session rather than on the URL.
I would so something like this.
var stringNumbers = intNumbers.Select(i => i.ToString()).ToArray();
var qsValue = string.Join(",", stringNumbers);
Request.Redirect("Page.aspx?numbers=" + sqValue);
Keep in mind that if there are too many numbers the query string is not the best option. Also remember that anyone can see the query string so if this data needs to be secure do not use the query string. Keep in mind the suggestions of other posters.
Note
If you are using .NET 4 you can simplify the above code:
var qsValue = string.Join(",", intNumbers);
Make the object serializable and store it in an out-of-process session.
All pages on your web application will then be able to access the object.
you could serialize it and make it printable but you shouldn't
really, you shouldn't
The specification does not dictate a minimum or maximum URL length, but implementation varies by browser and version. For example, Internet Explorer does not support URLs that have more than 2083 characters.[6][7] There is no limit on the number of parameters in a URL; only the raw (as opposed to URL encoded) character length of the URL matters. Web servers may also impose limits on the length of the query string, depending on how the URL and query string is stored. If the URL is too long, the web server fails with the 414 Request-URI Too Long HTTP status code.
I would probably use a cookie to store the object.

Creating a list of dataset fields and form fields for easy updating

I have a relatively complex dataset (numerous tables, some with multiple records) generated from reading in an XML file. I need to connect said dataset fields to an ASP form. At the moment I'm assigning them manually, like so in the pageload:
txt_first_init.Text = formData.ds.Tables["phrmHdrKey"].Rows[0]["first_init"].ToString();
txt_last_name.Text = formData.ds.Tables["phrmHdrKey"].Rows[0]["last_name"].ToString();
ddl_pregnancy_flag.SelectedValue = formData.ds.Tables["pPhrm"].Rows[0]["pregnancy_flag"].ToString();
And conversely when it's time to submit.
formData.ds.Tables["phrmHdrKey"].Rows[0]["first_init"] = txt_first_init.Text;
formData.ds.Tables["phrmHdrKey"].Rows[0]["last_name"] = txt_last_name.Text;
formData.ds.Tables["pPhrm"].Rows[0]["pregnancy_flag"] = ddl_pregnancy_flag.SelectedValue.ToString();
I did some looking into binding the textboxes (and dropdownlists, and checkboxes, and and and...) directly, but it seemed to be too many formats to use.
So this works fine, but as the number of fields increases, those load and unload lists are going to get unwieldy.
Trying to come up with a way to make a future update or addition so said list neater. I've gotten a very hand-wavy suggestion to place the two columns of names into a list, but unsure how to set such up, and how to load the items into a function that could evaluate and run the resulting commands.
Thoughts?
see here: Dynamic Form Generation in ASP.NET
looks like MS Dynamic Data is the answer.

Categories

Resources