unable to get checked property of htmlinoutcheckbox on server side(code behind) - html

I have created a html input check-boxes dynamically from code behind and after rendering the check-boxes on to aspx page I'm unable to get the checked property of those check-boxes on button click event. week is the enum with alldays of a week. Here the sample code.
HtmlInputCheckBox chkbx = new HtmlInputCheckBox();
chkbx.Attributes.Add("id", ((week)i).ToString());
chkbx.Attributes.Add("runat", "server");
chkbx.Attributes.Add("name", ((week)i).ToString());
chkbx.Attributes.Add("value", "checked");
HtmlGenericControl label = new HtmlGenericControl("label");
label.Attributes.Add("for", ((week)i).ToString());
if (i == 1 || i == 7)
{
label.Attributes.Add("class", "dow disabled");
label.Attributes.Add("disabled", "true");
}
else
{
label.Attributes.Add("class", "dow");
chkbx.Checked = true;
}
label.InnerText = ((week)i).ToString().Substring(0,2);
_dowcontrol.Controls.Add(chkbx);
_dowcontrol.Controls.Add(label);
ASPX page
<body>
<form id="form1" runat="server" method = "post">
<t2:mycontrol ID="SampleControl" runat="server" >
</t2:mycontrol>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>
</body>
ASPX.CS page
What should be inside button click?
Tried
Request.Form["***"], FindControl("***")

In order for your dynamically created controls to interact with viewstate, events and other stages in the page life-cycle, they need to be created in the Init event. Creating these controls later in the life-cycle will exclude them from taking part in post value binding, viewstate binding, etc. Also note that you must recreate the controls on EVERY postback.
protected void Page_Init(object sender, EventArgs e)
{
// Do any dynamic control re/creation here.
}

Related

How to use runat = "server" in input tag?

I'm writing in asp.net. When I add runat="server" property to my input tag, its value is null. When I remove runat="server" it works correctly. Who knows the reason?
I want change its property from code behind, that's why I wrote runat="server". However, the value is null.
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
string current_id = Session["Current_user"].ToString();
string a = Request.Form["newusername"];
string b = Request.Form["newpassword"];
string c = Request.Form["rewpassword"];
}
Code for control:
<input type="text" name="newusername" placeholder="Enter Username" required="required" runat="server"/>
When you add runat="server" and make the simple HTML control to asp.net HTML control, then asp.net renders the id and the name of that control in a manner that does not conflict with other asp.net controls on the same page.
So change the input to: (note now I add id, and remove the name!)
<input type="text" id="newusername" placeholder="Enter Username" required="required" runat="server"/>
and get the value using the post like this:
Request.Form[newusername.UniqueID]
or using the value:
newusername.value
other links to consider:
Accessing control client name and not ID in ASP.NET
Use newusername.Value to access the value of the control in your server side function.
Like
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
string current_id = Session["Current_user"].ToString();
string a = newusername.Value;
string b = newpassword.Value;
string c = rewpassword.Value;
}
You can't change an HTML control's properties using c# server side code. But you can do that using several other methods -
Method 1
you can use plain javascript or jquery to alter the HTML DOM element.
Method 2
you can create the HTML elements you want dynamically using HtmlGenericControl.
HtmlGenericControl username = new HtmlGenericControl("input");
username.attr("type", "text");
username.attr("name", "newusername");
And then you can append the controls into some div, like,
Front-End HTML code where you will add your dynamic controls-
<div id="dynaHtml" runat="server"></div>
Now, you can use that div to add your dynamic controls to page -
dynaHtml.Controls.Add(username);

How to access Input type="Checkbox" control inside <dx:ASPxGridView/>(Dev Express) at server side(c#)

I have a dx:ASPxGridView (Dev express gridview) which contains HTML checkboxes - input type="checkbox" control.
Problem is how can i access these HTML checkboxes at server side, so that i can check those checkboxes according to condition.
Please suggest me how can i access these HTML checkboxes on server side.
Code image can be found here
Thanks
Girish Rawat
First, to access a HTML element on a server, you need to mark it with the runat="server" attribute.
To access your checkbox, handle the ASPxGridView.HtmlDataCellPrepared event. In the event handler, you can get your input by using the ASPxGridView.FindRowCellTemplateControl method. You will also need to set ID for the input.
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False" OnDataBinding="ASPxGridView1_DataBinding" OnHtmlDataCellPrepared="ASPxGridView1_HtmlDataCellPrepared" KeyFieldName="ID">
<Columns>
<dx:GridViewDataCheckColumn VisibleIndex="0">
<DataItemTemplate>
<input id="check" type="checkbox" runat="server" />
</DataItemTemplate>
</dx:GridViewDataCheckColumn>
</Columns>
<Styles AdaptiveDetailButtonWidth="22"></Styles>
</dx:ASPxGridView>
protected void ASPxGridView1_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e) {
HtmlInputCheckBox check = (HtmlInputCheckBox)ASPxGridView1.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "check");
check.Checked = GetValue((int)e.KeyValue);
}
public bool GetValue(int id) {
// your logic
return id % 2 == 0;
}

Issue related to inbuilt javascript function of Telerik controls

I have asp.net webapplication having some telerik controls.
i have a RadTextBox(txtSearch) and RadButton(btnSearch) on .aspx page.
i have written following validation for empty Textbox:
$('#btnSearch').click(function () {
if ($('#txtSearch_text').val() == '') {
$('#txtSearch_text').addClass('validation');
return false;
}
else {
$('#txtSearch_text').removeClass('validation');
}
});
in validation class i have set Border-left:2px solid red
now problem is that when i click on btnSearch it sets validation class to txtSearch textbox, but when i use mouseover on txtSearch textbox class name suddenly changed to someother from inbuilt javascript function of Telerik. in this Javascript function of telerik TextBox, it changes class name of textbox to another class.
and this execution of change class occurs after executing custom javascript function.
so i want to execute customer javascript function after executing inbuilt functions of telerik. how to do it?
Thanks
You can define invalid states for RadInputs. RadTextbox by itself cannot be invalid because you can put anything in a textbox (unlike a numeric textbox, for example), yet here is a starting point:
<telerik:RadTextBox ID="RadTextBox1" runat="server">
<InvalidStyle BackColor="Red" />
</telerik:RadTextBox>
<asp:RequiredFieldValidator ID="TextBoxRequiredFieldValidator" runat="server" Display="Dynamic"
ControlToValidate="RadTextBox1" ErrorMessage="The textbox can not be empty!">
</asp:RequiredFieldValidator>
<telerik:RadButton ID="RadButton1" runat="server" OnClientClicked="test" Text="submit"
AutoPostBack="false" />
<script type="text/javascript">
function test() {
var tb = $find('RadTextBox1');
if (tb.get_value() == "") {
$find('RadTextBox1')._invalidate();
$find('RadTextBox1').updateCssClass();
}
}
</script>
Tampering directly with the HTML of complex controls may get you nowhere because they will try to update/fix their state according to the logic they have.

Using 2 buttons in same ASP.NET MVC Form

In general, is it possible to have two different buttons within the same form that post to different controller actions in ASP.NET MVC?
I am essentially trying to have two input (type="button") tags in the same form, but I want them to perform different controller actions. I would like to do this in a few cases because I think it provides a good aesthetic to be able to click buttons as opposed to hyperlinks. Is there a way to do this or should I design it differently?
Not really possible without using Javascript. With Javascript you'd just have to define different click handlers that invoked the proper action.
$(function() {
$('#button1').click( function() {
$(form).attr( 'action', '<% Url.Action( "action1" ) %>' )
.submit();
return false; // prevent default submission
});
$('#button2').click( function() {
$(form).attr( 'action', '<% Url.Action( "action2" ) %>' )
.submit();
return false; // prevent default submission
});
});
Some thoughts about handling this in the browser:
You can use links which are styled to look like buttons. This is easy to do, either with images or by putting the link in a block element with borders.
You can use two buttons which don't directly submit; they instead call a javascript function that sets the form action before submitting.
If all you want is something like OK & Cancel buttons, then have a look at this post by David Findley.
I'm using this method on my Edit view, where I have an Edit button and a Delete button. The delete button only requires the Id of the item. In the code below you can see that I've named my attribute "AcceptFormValueAttribute". This is method good for me, because my Delete [Get] action just shows a message asking for confirmation, so needs the redirect.
[ActionName("Edit")]
[AcceptFormValue(Name = "Action", Value = "Delete")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult EditDelete(int? id)
{
return RedirectToAction("Delete", new { id = id });
}
This has nothing to do with ASP.NET MVC but with html. The only way I see how you could do this is by modifying the action attribute of the form tag using javascript on submission of the form by checking which button was pressed.
Well there are a few ways you could handle this. Assuming you aren't sending data with the button click I'd go with option 3. If data must be included then consider option 1 with some sort of temporary data store (like TempData).
One form posts to one controller
action on submit and the controller
action checks which button was
clicked and then dispatches a
RedirectToAction(). (Not great)
Multiple forms on one page post to multiple controller actions (Better)
Inside or outside a form create an input type="button" and give it an onclick handler
that redirects the user to a controller action (Best)
Haven't tried this, but given the ID of the clicked button does get sent VIA http POST, you could probably do something like:
<input type="submit" name="GO" ID="GO" value="GO BUTTON" />
<input type="submit" name="STOP" ID="STOP" value="STOP BUTTON" />
Then on the mvc end, just have two methods, one with a go parameter, one with a stop parameter.
Method #1
How about using two different forms wrapping the buttons, then using CSS to position one of them so that it appears (visually) to be inside the "main" form?
A really quick example:
<fieldset id="CombinedForm">
<form ... action="Method1">
...form stuff here...
<input id="Button1" type="submit" value="Do something">
</form>
<form ... action="Method2">
...form stuff here...
<input id="Button2" type="submit" value="Do something else">
</form>
</fieldset>
...Then using CSS as follows:
#CombinedForm {
position: relative;
padding-bottom: 2em; /* leave space for buttons */
}
#Button1, #Button2 {
position: absolute;
bottom: 0;
}
#Button1 {
left: 0;
}
#Button2 {
right: 0;
}
The result should be that you have a fieldset or div which looks like a form, having two actual HTML forms inside it, and two buttons which are positioned within the parent box, yet submitting to different locations.
Method #2
Another method occurs: have both buttons in the same form, pointing to one controller action, that then decides (based on the value of the button clicked) which action to redirect to.
Its not Javascript required...
how about this
public ActionResult DoSomething()
{
// Some business logic
TempData["PostedFormValues"] = Request.Form;
if (Request.Form("ButtonA") != null)
{
return RedirectToAction("ActionA", RouteData.Values);
}
return RedirectToAction("ActionB", RouteData.Values);
}
I think that I can suggest more simple one.
For example you have two buttons : ButtonA,ButtonB and want to perform different
action on each one.
Simplest solution is : just use BeginForm statement:
#using ( Html.BeginForm("ButtonA" , "Home") )
{
<input type="submit" value="ButtonA"/>
}
#using ( Html.BeginForm("ButtonB" , "Home") )
{
<input type="submit" value="ButtonB" />
}
You must also declare ButtonA,ButtonB actions in your Home controller :
[HttpPost]
public ActionResult ButtonA()
{ . . . }
[HttpPost]
public ActionResult ButtonB()
{ . . . }

updatepanel __dopostback hits .update() but does not refresh

I have a page with two update panels each of which has a gridview generated dynamically. Updatepanel1 refreshes every ten seconds on a timer. The second update/grid refreshes when an item is selected in the first grid.
I'm trying to accomplish this feat using __doPostBack. This method does reach the server and run my .update on updatepanel2. I see that updatepanel2 gets data, but the form never actually updates updatepanel2.
I can get updatepanel2 to display data only when updatepanel1 timer ticks and I set updatepanel2 mode to "Always".
anyone have any suggestions?
Thanks
Well I fixed this problem. I modified to using the following method for the doPostBack call.
http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript/
Hope this helps.
I see you answered your own question, but for the benefit of others, instead of doPostBack(), why not set both on a Timer to refresh at a specified interval, or as a Tick event method with an "UpdatePanel1.Update()" at the end of the method? For this way, you'd need to set the interval in the Default.aspx page code itself; I picked 10ms so it could show the progress for a very fast operation:
<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="360000" />
<asp:Button ID="btnDoSomething" runat="server" Text="Do Something" OnClick="btnDoSomething_Click" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load" UpdateMode="conditional">
<ContentTemplate>
<span id="spnLabel" runat="server">
<asp:Timer ID="Timer1" runat="server" Interval="10" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
<Triggers >
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
Then have a Timer1_Tick method in the code-behind that you call when you have an update - in this example, something to add to spnLabel.InnerHtml from a btnDoSomething_Click() method:
protected void btnDoSomething_Click(object sender, EventArgs e)
{
Timer1.Enabled = true;
Timer1.Interval = 10;
Timer1_Tick(sender, e);
Timer1.Enabled = false;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
spnLabel.InnerHtml = "hi";
UpdatePanel1.Update();
}
Remember that the refresh is controlled by the Timer interval, not by when you call Timer1_Tick(sender,e), even if you have an UpdatePanel1.Update() at the end - example, if you set the interval to 10000, it would update after 10 seconds, even if your operation had used the Timer1_Tick() method several times before then. You would still need an UpdatePanel1.Update() at the end, regardless, though.
-Tom