In asp.net, you can use asp:Repeater for dynamically generating controls.
for example:
<asp:Repeater runat="server" id="rpt">
<ItemTemplate>
<asp:Textbox runat="server"/>
</ItemTemplate>
</asp:Repeater>
Then you can get loop through the items on the server side:
foreach(var items in rpt.Items)
{
}
And in MVC, you can do something like this:
#foreach(var item in model)
{
#Html.TextBoxFor(a=>item.searchCriteria);
}
But there is a problem:
I would like to generate textboxes when ever user clicks add more textbox button:
If I use foreach in MVC, then I won't be able to fetch the user input on the controller, also, I don't have a model to loop through.
And the final desired output will be:
After the user clicks the "Add more textbox" button, a new textbox will be append to the bottom, and after the user clicks the search button, the text inside the textbox will be generated into a query string, something like this:
View:
<input name="searchCriteria" type="text" class="form-control" />
<input name="searchCriteria" type="text" class="form-control" />
<input name="searchCriteria" type="text" class="form-control" />
<input name="searchCriteria" type="text" class="form-control" />
Controller:
public ActionResult Search()
{
string queryString = Request.RawUrl;
//parse the querystring here
return View(NumberOfVisitorsReport);
}
And the query string generated will be:
www.website.com/?searchCriteria=a&searchCriteria=b&searchCriteria=c
So are there any alternative way to achieve this in MVC?
Edit:
I've took a look at some post on "How to generate controls dynamically in MVC"
For example
Control creation based on model value in MVC4
He is generating controls based on value in database, if I implement this to my website, the controls will lose value on each post back.
You probably want to move away from "postback" and look to adding text boxes dynamically in the browser using jQuery or a similar framework. If you either name the new text boxes carefully or do the submit as an AJAX post of a JSON object, you can harvest all the values from all the added controls.
You must use jquery.
This article can help for solve to problem.
Dynamic Form in Asp.net MVC & jquery
You are going to have to use For loop insead of ForEach. Then use the index to Create new Textbox controls, this way when you submit the form, index of newly created textbox will be submited, you can even BIND it to a model if the data type of your model is LIST.
Example:
#for (int i = 0; i < Model.Contributor.Count(); i++)
{
#Html.HiddenFor(model => Model.Contributor[i].Id)
}
now you know the value/index of "i", use that to populate new controls.
Related
I am working on an asp.net page where I am saving user input into my database using TextBox e.g ***<asp:TextBox ID="code" runat="server" Width="155px"></asp:TextBox>***
in this case I'm getting the ID of the TextBox as "code" so i can capture the values from that TextBox. Now i have a jQuery texbox <input type="text" id="date" required="required"/> where "date" is jQuery function ID. Which attribute or ID should i use to capture the user input and save them into my database using this <input type="text" id="date" required="required"/> textbox..?
you can change your plain textbox to asp textbox
<asp:TextBox Id="date" runat="server" required="required" />
if not than you can get values of plain Html elements in code behind.
Write a function to set the value of "date" textbox to a hidden
field
Than capture the value of hiddenfield in your code behind
Hope this helps
Why not simply turn that field into a asp.net control as well?
Would be:
<asp:TextBox Id="date" runat="server" required="required" />
It will be rendered as a input type="text" to the browser anyway and should work just fine.
In order to find the control (since ASP.NET sometimes have the odd interest in prefixing controls) you can just use $find in your script. Or, as someone pointed out, use class selectors (i.e assign a CssClass attribute to your TextBox) and use that as selector in your jQuery code.
That way the date value will be available both to server side operations and client side.
you can use Asp.Net textbox as jquery datepicker, just use class selector to convert into jquery ui date picker
I'm a C#/VB developer trying to migrate away from aspx and web forms towards HTML.
I'm trying to do this:
HTML
<input type="radio" id="rb" runat="server" />
C#
DataTable dt = clsMyClass.GetItemTable();
rb.DataSource = dt;
rb.DataValueField = "ItemID";
rb.DataTextField = "ItemName";
rb.DataBind();
Thanks.
Ok, you can use the controls provided by the Microsoft ASP.NET Web Forms to control what and how the User interacts with the Application that you're providing him with.
Actaully what those controls provide you is that you Validate the data on the server side as well as client side. The keyword, runat="server" is used to tell the server that this Element should be handled on the Server.
If you want to redesign your application you can do that too. Instead of doing anything, just simply use your own Controls.
<input type="text" onchange="function()" />
In the JavaScript you can handle the events on that element.
function () {
/* some validations */
}
runat="server" is just to ensure that whenever the control's value is changed or any other particular functions are triggered the server would execute some method to take control of that.
Similarly, if you're not using Web Forms. You can create your own custom Controls and your own custom events to handle all the methods and events.
For example, if you have this control
<input type="text" name="myName" />
jQuery would be handy in this
$('input[name=myName]').change(function () {
alert('Hi, ' + $(this).value);
}
This way, once a user changes the value, he would get an alert for Hi, [name_of_user]. If I were to write Afzaal Ahmad Zeeshan, it would pop up
Hi, Afzaal Ahmad Zeeshan.
Now let's give the whole form control. Sample form is
<form method="post">
<input type="text" name="myName" />
<input type="text" name="id" />
<input type="submit" value="Submit" />
</form>
jQuery would be
$('form').submit(function () {
/* send data to server */
}
On the server side, handle those fields and then save them.
What are you trying to achieve? Are you trying to bind these elements with contents from your database or simply trying to add some text...
You can make a function in your codebehind to catch the data from your database and simply write it to your input controls by using response.write methods...
UPDATE
Hey!!! how about a function in codebehind like ....
public string getTheValueFromDataBase()
{
string abc = "";
abc = "text from database over here...";
return abc;
}
IN HTML PAGE
<input type="radio" /><%Response.Write(getTheValueFromDataBase()); %>
I want to get the value of my input tag into my C#.
<div id="datetimepicker2" class="input-append">
<input data-format="MM/dd/yyyy HH:mm:ss PP" type="text"></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar">
</i>
</span>
</div>// what should we use here?
The value is set by the user of the page.
I did't understand which control value you want to get. But If you want to get input element value into the code behind, you need to set runat="server" attribute, because this is a simple html element not a Asp control.
Add runat="server" and id="your_id" and you should have access to them.
for example:
<input type="text" value="Username" class="input-text autoclear"
runat="server" id="myTextBox" />
than you can simply get value of input box like this:
string myStringFromTheInput = myTextBox.Value;
For more options please See here
Try this
Add name for your input type
<input data-format="MM/dd/yyyy HH:mm:ss PP" name="txtBox1" type="text"></input>
and try this way for get value in codebehind
string value=Request.Form["txtBox1"];
You can access all your submitted form data at server side by looking into the form Request object.
Ex. Request.Form["txtDate"] OR Request["txtDate"].
Naming the html elements makes easier to look into form collection for specified element.
If what you posted is your actual code, you have an extra space in your closing tag
</asp: TextBox>
Should be
</asp:TextBox>
and then txt_todata.text should work
I am populating a ListView with HTML from a database using a Literal with Text='<%#Eval("HTMLData")'%>. When I trigger a PostBack, changes to the loaded HTML are not being reflected in litRowData.Text.
ViewState is enabled for the page, the ListView, and the Literal in the ItemTemplate, and I am making sure to only populate the ListView with initial values from the database when if(!IsPostBack) is true in Page_Load.
<asp:ListView ID="lvForm" runat="server"
DataKeyNames="RowID" ItemPlaceholderID="phRow"
EnableViewState="true">
<LayoutTemplate>
<asp:PlaceHolder ID="phRow" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<asp:Literal ID="litRowData" runat="server" Text='<%#Eval("HTMLData")%>'
EnableViewState="true"></asp:Literal>
</ItemTemplate>
</asp:ListView>
I need to be able to capture changes to the contents of the loaded HTML controls. Since this HTML comes from a database table, I can't just use ASP controls inside the ItemTemplate. Can anyone see something I'm missing, or suggest an alternative way to do this?
Edit:
To clarify a little more, I'm trying to load form input elements dynamically from a database, render them as HTML controls on the page, allow the user to modify their contents by entering text or selecting options, then capture the modified HTML and save it back to the database when the user clicks a save button.
The way postback works in .NET is actually a wrapper around the more basic idea of HTML forms. A basic example of HTML forms is:
<html>
<body>
<form action="" method="POST">
<input type="text" value="type here" />
<input type="submit" value="go" />
</form>
</body>
</html>
Roughly, what the .NET abstraction adds is:
<html>
<body>
<form action="" method="POST">
<input type="hidden" name="__VIEWSTATE" value="string-encoded-value" />
<input type="text" name="bob" value="type here" />
<input type="submit" value="go" />
</form>
</body>
</html>
Whereby on postback to your page, all input elements with names are mapped back into properties of your Page object, and the __VIEWSTATE hidden field is deserialized into all properties of objects that do not correspond to values of html input tags. For example, if Page.bob had a DateTime property associated with it, it would be stored in __VIEWSTATE possibly.
ASP.NET Literal tags in Page markup will get printed into the browser exactly as is, meaning that if you have <span>bob</span> as its value, that is how it will appear within the <form> tag. However, in plain HTML world, <form> tags when posted will only contain the values of certain form elements (aka not every div, span, p etc. gets posted back, only input, select, textarea and some others). So if your literal doesn't contain an input then it won't even get posted back meaning __VIEWSTATE will be used to restore the Value property of the Literal back to its initial state.
To fix this, you probably don't want to stick html into a Literal because even if you do it's not clear that it will get associated with the right property of your page. Instead, try a TextBox element or something else that gets written as an input element directly by the ASP.NET webforms code. Alternatively, try using javascript to allow modifications of flat text in divs if you don't need to persist the data.
This answer builds on the prior one now that you have a .NET TextBox control that is correctly posting back the value of edits. Right below it, you can add to code behind:
protected void Page_Load(object sender, EventArgs e)
{
litRowData.Attributes.Add("onKeyUp", "WriteText(this.value)");
}
Html:
<ItemTemplate>
<asp:TextBox ID="litRowData" runat="server" />
</ItemTemplate>
<div id="yourPreview"></div>
<script type="text/javascript">
function WriteText(val){
document.getElementById("yourPreview").innerHTML=val
}
</script>
I think I may have used a repeater when I should have used something else, so I'm ready to chalk this up to design but I wanted to check with the development community before changing this.
I should also say upfront that I'm using this repeater control within a custom user-control for an aspx page.
My situation is that I have to dynamically display a list of additional parts when a user selects an item. This is similar to an "you might also be interested in" list that you sometimes see during an online checkout.
So the user selects an item to order from a dropdown and up to 4 additional parts can be optionally added.
Currently I'm bringing back that optional part list in a generic list of data-objects and binding it to a repeater control and its textboxes. The textboxes basically list a part description in one box and an option for the user to type in a quantity of how many they want of that item in another textbox.
That all works great.
So to be clear, after the repeater control loads everything and the form is rendered, the users can then type in values in the quantity textboxes.
Since this is all in a user-control, I'm writing a method to gather all this information up, populate a business object and return it to whatever calls it.
I'm having trouble finding the auto-generated textboxes so I can retrieve their values.
I have this sneaking suspicion that I'm doing something obviously wrong in my design. So I wanted to run this by the hive-mind to see what others think :)
Here is my markup generated by the repeater control.
<div class="base-container-controls-75pct">
<div class="base-container-controls-98pct">
<div class="base-container-controls-75pct">
<input name="DownLoadItem1$UxAdditionalParts$ctl01$UxItemNumber" type="text" id="DownLoadItem1_UxAdditionalParts_ctl01_UxItemNumber" class="textbox-readonly-xl" />
</div>
<div class="base-container-controls-10pct">
<input name="DownLoadItem1$UxAdditionalParts$ctl01$UxQuantity" type="text" value="3" id="DownLoadItem1_UxAdditionalParts_ctl01_UxQuantity" class="textbox-md" />
</div>
</div>
... more repeating code here, basically the 98pct div above is repeated for each "row" ...
</div>
I basically figured this out one after piecing some things together, reading various other posts.
What I was missing was that I need to add [EnableViewState="True"] to the markup for my repeater. So my markup is below:
<asp:Repeater ID="UxAdditionalParts" runat="server" OnItemDataBound="UxAdditionalPartsItemDataBound" EnableViewState="True">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="base-container-controls-98pct">
<div class="base-container-controls-75pct">
<asp:TextBox ID="UxItemNumber" runat="server" CssClass="textbox-readonly-xl"></asp:TextBox>
</div>
<div class="base-container-controls-10pct">
<asp:TextBox ID="UxQuantity" runat="server" CssClass="textbox-md"></asp:TextBox>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Once this was done, I could simply loop through the controls as I expected and grab their values, building my list of objects from them. Here is how that turned out:
// Find all textboxes, looping through them to build an object list. Generally there is a maximum of 4 parts
// associated here but there could be more in the future so this should expand too.
for (int j = 0; j <= UxAdditionalParts.Items.Count - 1; j++)
{
if (UxAdditionalParts.Items[j].ItemType == ListItemType.Item || UxAdditionalParts.Items[j].ItemType == ListItemType.AlternatingItem)
{
TextBox txtItm = (TextBox)UxAdditionalParts.Items[j].FindControl("UxItemNumber");
TextBox txtQty = (TextBox)UxAdditionalParts.Items[j].FindControl("UxQuantity");
if (txtItm != null & txtQty != null)
{
// Create a new part and add it to our list.
AdditionalPart objAdditionalPart = new AdditionalPart();
objAdditionalPart.ItemNumber = txtItm.Text;
objAdditionalPart.Quantity = Convert.ToInt32(txtQty.Text) ;
loAdditionalParts.Add(objAdditionalPart);
}
}
}
Mystery solved!