I have a View that is meant to display a question and several radio buttons representing possible answers to the question. The number of possible answers changes with each question, so I need to find a way of generating the radio buttons dynamically. I am new to aspx syntax and am not quite sure how to go about this, i.e. how to I display the collection of radiobuttons I created in the script in the html below? Would using RadioButtonList be better for this?
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<UncleBobWebService.Models.MultipleChoiceQuestion>" %>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title>Application</title>
<link href="/Theme/UncleBobTheme.css" rel="Stylesheet" />
<script lang="cs" runat="server">
protected void Page_Load(Object o, EventArgs e)
{
int count = Model.PossibleAnswers.Count;
List<RadioButton> radioButtons = new List<RadioButton>();
for (int i = 0; i < count; ++i)
{
RadioButton button = new RadioButton();
button.ID = "1";
button.GroupName = "answers";
button.Text = Model.PossibleAnswers[i+1].TheAnswer;
button.Checked = false;
radioButtons.Add(button);
}
}
</script>
</head>
<body>
<h2>Question</h2>
<div class="body">
<form id=form1 runat=server action="/ApplicantApply/FormAction">
<div class="box">
<div class="left-justify">
<div><%= Html.DisplayFor(Model => Model.Question) %></div>
<!-- How to display the radiobutton list here instead of below? -->
<input type="radio" id="yesAnswer" name="yes" value="Yes">Yes<br />
<input type="radio" id="noAnswer" name="no" value="No">No<br />
</div>
</div>
<input type="submit" name="submit" value="Previous" />
<input type="submit" name="submit" value="Next" />
</form>
</div>
</body>
</html>
Seems like you're mixing ASP.NET & ASP.NET MVC
If you're Using ASP.NET MVC:
<% for (int i = 0; i < Model.PossibleAnswers.Count; ++i) { %>
{
<label>
<%= Html.RadioButtonFor(m => m.PossibleAnswers[i].TheAnswer, m.PossibleAnswers[i]..ID) m.PossibleAnswers[i].TheAnswer %>
</label>
<% } %>
If you are using ASP.NET:
Use RadioButtonList for this purpose. It is better suited for such operations.
One way could be to declare the control in your aspx file and then on PageLoad event you can add items/bind it to the collection.
IMHO Binding is a generally a better option.
Binding Example:
http://asp-net-example.blogspot.com/2009/03/how-data-bind-radiobuttonlist-on-button.html
Adding Example:
protected override void OnInit(EventArgs e)
{
RadioButtonList1.Items.AddRange(GetItems());
base.OnInit(e);
}
private ListItem[] GetItems()
{
return new ListItem[] {
new ListItem("Item 1", "1"),
new ListItem("Item 2", "2"),
new ListItem("Item 3", "3"),
new ListItem("Item 4", "4")
});
}
You're mixing Asp.net WebForm example code with an Asp.net MVC view. You don't want to use Page_Load or any Asp.net server controls in MVC. You want to use Html.RadioButton()
<div class="left-justify">
<div><%= Html.DisplayFor(Model => Model.Question) %></div>
<% for (var i=i; i<=Model.PossibleAnswers.Count(); i++) %>
<label><%= Html.RadioButtonFor(m => m.PossibleAnswers[i], "Yes")> %> Yes</label>
<label><%= Html.RadioButtonFor(m => m.PossibleAnswers[i], "No")> %> No</label>
<% } %>
</div>
These things are called Html Helpers by asp.net. You can google that term to find examples of them. They exist for most of the common form elements.
You can use the below links.
http://www.developerscode.com/2011/02/how-to-create-dynamic-registration-form.html
dynamically created radiobuttonlist
http://csharp-guide.blogspot.in/2012/05/adding-radiobutton-options-dynamically.html
http://forums.asp.net/t/1192583.aspx/1
http://www.codeproject.com/Questions/360219/radio-button-dynamic-creation
ASP.net creating dynamic Radio Button List
Hope this will help you.
display answer and question on page.but the question answer display option type wise and the option type is multipal choice single answer,multipal answer multipal choice,image date.
if answer tabel option type field set if set 1 so display data in radio button wise in gridview to so to create this page in asp.net
Related
I have a aspx page and i want to hide the button from cs file based on my some condition
My .aspx looks like :
<asp: Content Id="contentid" >
<% if (!IsRedeemCardFlowOptin)
{ %>
<ul id="ulid" class="abc">
</ul>
<div class="bcd" id ="div1">
<div id="div2"></div>
<div id="div3"></div>
<div id="div4" runat="server">
<h4><%= m_AutoRenewInfo.NewPageContent.ArCsidOffHeader%></h4>
<button class="abc bcd cde" title="Button" id="buttondiv"><span>Button</span></button> //Want to hide this button
</div>
</div>
<% } %>
</asp:Content>
Now in the cs file i want to hide the button with id "buttondiv", how can i do that
In my cs file, i try this 2 things but it doesnt work
Control myDiv = (Control)FindControl("buttondiv");
myDiv.Visible = false;
Or
foreach (Control c in contentid.Controls)
{
if (c.ID == "buttondiv")
{
c.Visible = false;
}
}
Can anyone let me know
In order to be used as a server-side control, the button would need to be a server-side control. Add runat="server":
<button class="abc bcd cde" title="Button" id="buttondiv" runat="server">
Then (unless you've broken the designer somehow, it's been a while since I've used Web Forms) you should have an HtmlControl object in your class that you can set without the need to "find" the control:
this.buttondiv.Visible = false;
Kindly keep this in css file.
#buttondiv{
display:none;
}
Or apply style inline like below:
<button class="abc bcd cde" title="Button" id="buttondiv" style="display:none"><span>Button</span></button>
Here is my page:
<%# Page Language="C#" MasterPageFile="~/FBMaster.master" CodeFile="ViewOffer.aspx.cs" Inherits="ViewOffer" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<%
FlightBookingWS.FlightBookingSoapClient client = new FlightBookingWS.FlightBookingSoapClient();
FlightBookingWS.Offer offer = client.GetOffer(Request.Form["OfferID"]);
if (offer != null)
{
%>
<div class="OfferDiv">
<span><b>Origin Airport: </b><%=offer.OriginAirport ?? "" %></span>
<span><b>Destination Airport: </b><%=offer.DestinationAirport ?? "" %></span>
<span><b>Airline: </b><%=offer.Airline ?? ""%></span>
<span><b>Available Seats: </b><%=offer.AvailableSeats%></span>
<span><b>Number Of Connections: </b><%=offer.NumberOfConnections%></span>
<%
if (offer.Fare != null)
{
%>
<span><b>Fare: </b><%=String.Format("{0:0.00} {1}", offer.Fare.Value, offer.Fare.Currency) %></span>
<form runat="server">
<span>
<input type="hidden" id="OfferIDField" runat="server" />
<input type="hidden" id="MessageField" runat="server" />
<b>Number of Seats: </b>
<asp:TextBox ID="NumSeatsField" runat="server" Text="1" />
<asp:Button runat="server" Text="Book now" />
</span>
</form>
<%
}
}
else
{
%>
Offer not found.
<%
}
%>
<div id="ErrorBox" runat="server"></div>
</div>
</asp:Content>
Whenever I submit the form, the keys used in the post data are changed from the IDs I wrote to the following ones:
Ideally I'd like to access them using the same keys as the IDs of the inputs they came from, like in normal HTML.
That's not how ASP.NET web forms work
When you put markup on a page with the runat="server" attribute, you are not actually writing page markup. You are defining server-side controls that emit page markup. You're not meant to use them like actual HTML elements.
When the page is posted back, the ASP.NET framework looks at the request message and parses all of the values. It then populates the server-side controls with the necessary data so you can retrieve it easily using ASP.NET syntax.
So, instead of
var offerID = Request.Form["ctl100$ContentPlaceHolder1#OfferIDField"]
you should simply use
var offerID = this.OfferID.Text;
This is the way ASP.NET web forms work.
The old-fashioned way
If you'd rather do it the old-fashioned way, remove the runat="server" attribute and write your markup like regular HTML:
<INPUT ID="OfferID" Name="OfferID">
...and then you can read it the "normal" way:
var offerID = Request.Form["OfferID"];
I am working on SharePoint to create a Feedback questionnaire form using an application page that is basically a aspx page.
I wish to do this by emulating MVC as far as possible. I've set up my model in the code-behind:
public List<QuestionViewModel> modelQuestions = new List<QuestionViewModel>();
Next, I need to display each question and an appropriate input depending on the question type (e.g. single line, multi line, single selection, multiple selection).
I've got it displaying the questions correctly:
<fieldset class="what-went-wrong">
<% for (int i = 0; i < modelQuestions.Count; i++) { %>
<p>
<label for="QuestionText">
<% if (modelQuestions[i].Required) { %>
<span class="req-field indicator">*</span>
<% } %>
<%= modelQuestions[i].QuestionText %>
<% if (modelQuestions[i].Required) { %>
<span class="req-field right">* Required field</span>
<% } %>
</label>
</p>
<% } %>
</fieldset>
This give's me the question text. I'm now trying to construct the appropriate input, but this <% %> tags is not working for this:
<% if(modelQuestions[i].QuestionTypeId == QuestionType.SingleLine) { %>
<input id="modelQuestions_<% i %>" name="modelQuestions[<% i %>]" type="text" placeholder="<% modelQuestions[i].Placeholder %>" />
<% } %>
I can't seem to get it to construct the html element using details from the model (in the value for id, name, placeholder etc.)
Also, I've no idea how to go about posting this back to the server when I get to that point.
Is there any merit in continuing? Are there other controls/methods more appropriate to use in this case with aspx?
You cannot generate HTML markup like this. Even data-binding expressions will not help, because they bind ASP.NET controls' attributes values, not the plain output HTML in the page.
You should generate the markup in the "code behind", like this:
Page markup:
<div id='AnswersPanel'>
<div>
Page code behind:
protected void PageLoad(...)
{
AnswersPanel.InnerHtml = "";
AnswersPanel.InnerHtml += string.Format("<input id='modelQuestions_{0}' name='modelQuestions[{0}]' type='text' placeholder='{1}' />",
i.ToString(),
modelQuestions[i].Placeholder);
}
I am new to C# (my job is making me convert from JavaScript) and for some reason I cannot find a straightforward example of setting up a button that calls a method.
I am using C# ASP.NET MVC 2 with the ASPX view engine. This is not ASP.NET Web Forms.
My Index.aspx looks like:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Blogs
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Blogs</h2>
<button ID="btnBlog" onclick="blogging" runat="server">Blog</button>
</asp:Content>
and I have tried several ways of doing this; this last one being:
public event EventHandler blogging()
{
System.Diagnostics.Debug.Write("clicked");
}
Edit:
Ok so doing the button like:
<asp:Button ID="btnBlog" OnClick="blogging" runat="server" />
and method:
protected void blogging(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write("clicked");
}
Tells me that blogging is undefined... how do I call blogging()?
If you meaning to call an action method from View then you might try to use one of the following examples below. When creating a link to a controller action in ASP.NET MVC, using the generic ActionLink method is preferable, because it allows for strongly typed links that are refactoring friendly.
Default: ActionLink:
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
However, what if we want to have an image that links to an action? You might think that you could combine the `ActionLink` and Image and `Button` helpers like this:
Using Button:
<button onclick="location.href='#Url.Action("Index", "Users")';
return false;">Cancel</button>
(with parameters)
<button onclick="location.href='#Url.Action("Detail", "Admin",
new { Model.ProductID })';return false;">Detail</button>
or
<input type="button" title="Delete" value="Delete"
onclick="location.href='#Url.Action("Delete", "movies", new { id = item.ID })'" />
**Using Image:**
<a href="#Url.Action("Delete", "movies", new { id = item.ID })" title="Edit">
<img src="../../Content/Images/Delete.png" />
</a>
I have a blank page with two buttons.
the first button's click code is this:
Session["permissionUser"] = "1";
and here's the second button code:
Session["permissionUser"] = "2";
and then i have a hyperlink which redirects to the "main" website.
my objective is to adapt the menu bar which is on the masterpage based on the permission saved in the session. here's part of my code in the masterpage:
<body>
<div id="menuBar">
Home
<% if (Session["permissionUser"] == "1"){ %>
PERMISSION 1 LINK
<% } %>
<% if (Session["permissionUser"] == "2"){ %>
PERMISSION 2 LINK
<% } %>
</div>
<div id="content">
<asp:ContentPlaceHolder ID="websiteContent" runat="server"></asp:ContentPlaceHolder>
</div>
</body>
the problem is when i run the application, even if i click any of the buttons the menu doesnt adapt at all. it just shows the hyperlink "Home" and not any of the others which were supposed to be shown since the session is either 1 or 2 (depending on which button i clicked)
i cant really see what im doing wrong so if you guys have any suggestions i'd be really grateful
Your code is very PHPish. That is to say, it's ugly. And unwieldy. Let's put the logic in the code behind. We also need a form so we can have controls that run on the server.
public void Page_Load(object sender, EventArgs e)
{
//you should probably also check to make sure the session has "permissionUser" in it
if (Session["permissionUser"] == "1")
{
Permission1HL.Visible=true;
}
else if(Session["permissionUser"] == "2")
{
Permission2HL.Visible=true;
}
}
And change your ASPX page to this.
<body>
<form runat="server">
<div id="menuBar">
Home
<asp:HyperLink runat="server" id="Permission1HL" Text="Permission 1 Link" Visible="false" />
<asp:HyperLink runat="server" id="Permission2HL" Text="Permission 2 Link" Visible="false" />
</div>
<div id="content">
<asp:ContentPlaceHolder ID="websiteContent" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>
I suggest that you make a serverside hyperlink control instead, and set the text and navigateurl from codebehind
<asp:HyperLink id="hyperlink1"
NavigateUrl="http://mydefaulturl.com"
Text="DefaultText"
runat="server"/>
from code behind:
if (Session["permissionUser"] == 1)
{
hyperlink1.NavigateUrl = "#"
hyperlink1.Text = "Permission 1 link"
}...
This will allow you to better control and debug your values.
I would actually be more specific in the if statement
<% if (Session["permissionUser"].toString() == "1"){ %>
with null checks
<% if (Session["permissionUser"] != null && Session["permissionUser"].toString() == "1"){ %>