How do I set a click event in C#? - c#

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>

Related

ASP form parameter names being changed to include the master page contentplaceholder

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"];

Use model on SharePoint application page .aspx

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);
}

Jquery event in ASP MVC 3 Web Application

I am developing an ASP.Net MVC 3 application using C# and SQL Server 2005.
I would like to create a Jquery event on a button. It's like an accordian animation.
I have already in the template which I used an example and I want to remake it in an another button.
This is a video describing the event.
Sorry, I didn't post any code because I don't find really where is the script of this event.
But, I will edit my post for any demand.
Thanks for understanding :)
this is The view Gestion which I would like to show when I click on the button :
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.FlowViewModel>" %>
<asp:Content ID="loginTitle" ContentPlaceHolderID="TitleContent" runat="server">
Gestion
</asp:Content>
<asp:Content ID="loginContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>GĂ©rer</h2>
</asp:Content>
This is a class GestionHelper which I created following the example of the other button :
namespace Helpers
{
public static class GestionHelper
{
public static string GestionLinkHelper(this HtmlHelper helper){
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
var sb = new StringBuilder();
sb.Append("<div id=\"gestionlink\">");
sb.Append(helper.ActionLink("aaaaa", "Gestion", "Anouar"));
sb.Append("</div>");
return sb.ToString();
}
}
}
I creat a new Controller named AnouarController :
namespace MvcApplication2.Controllers
{
[HandleError]
public class AnouarController : Controller
{
//
// GET: /Anouar/
public ActionResult Gestion()
{
return View();
}
}
}
and finally,,,this is what I add in the View of the link (which allow the action):
<%= Html.GestionLinkHelper() %>
If I understand you, add a button and your target div
<input type="button" value="Show Gestion" id="btnShowGestion" />
<input type="button" value="Hide Gestion" id="btnHideGestion" />
<div id="divGestion"></div>
Add your JQuery On Ready
<script type="text/javascript">
$(document).ready(function() {
$('#divGestion').load('/Anouar/Gestion');
$('#btnShowGestion').click(function() { $('#divGestion').show() });
$('#btnHideGestion').click(function() { $('#divGestion').hide() });
});
</script>
Not knowing what Ajax action you wanted to perform, I assumed you wanted to load a partial view into a div.

Generating a number of radio buttons dynamically in aspx

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

View loop value doesn't change after first value

I have an ICollection<String> being passed to my view and I do a foreach to load a partial view. It loops through the correct number of times, however, the value it passes is the same and I know in the model that this is not the case.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index", new List<String>());
}
[HttpPost]
public ActionResult Index(List<String> txtValue)
{
return View("Index", txtValue);
}
}
View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<String>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
//Deletes the div the Control is in.
$(".delete").live("click", function () {
$(this).parent().remove();
});
//Adds the TextBoxes to divControls
function AddTextBox(Value) {
var elements = "<div><input name=\"txtValue\" type=\"text\" /><input type=\"button\" class=\"delete\" value=\"-\" /><br/></div>";
$("#divControls").append(elements);
}
</script>
<h2>Controls!!!</h2>
<input id="btnAdd" type="button" name="Refresh" value="+" onclick="AddTextBox()" />
<% using (Html.BeginForm())
{ %>
<input id="btnsubmit" type="submit" name="Submit" onclick="Submit" />
<div id="divControls">
<%
foreach (var text in this.Model)
{ %>
<%=Html.TextBox("txtValue", text, new { id = "Value", name = "txtValue" })%>
<% Html.RenderPartial("TextControl", text);
}
%>
</div>
<%
}
%>
</asp:Content>
TextControl.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
<div>
<%=Html.TextBox("txtValue", this.Model, new { id = "Value", name = "txtValue" }) %>
<input id="btn" type="button" class="delete" value="-" /><br/>
</div>
The values of the model passed from the controller to the view are correct, even when passed to the user control "TextControl" the value is correct, but when the Textbox displays they are all just the first value of the original model passed in.
Ex.
Model as List<String> { "1", "2", "3", "4" }
passed to the view, will iterate through each one correctly, passing the correct string to "TextControl" to create a Html.TextBox("name", this.Model). Everything on the debugging side appears correct, however, when it finishes all the textboxes are "1" (or the first value in the list).
Here's a link to my exact code: http://www.sendspace.com/file/sypl1u
Note:
I came up with a solution of just using <input type="text" name="txtValue" value="<%= this.Model %>" /> instead.
Potential issue: you are using ElementAt which is LINQ method that fave special behavior for IList argument, but you are passing in txtValue as result of some query. In this case ElementAt may case sequence to be enumerated multiple times and may even fail if sequence can't be re-enumerated.
Consider simple foreach on the collection instead:
foreach (var text in Model)
{
Html.RenderPartial("TextControl", text);
}

Categories