How can I access an asp drop down lists selected value that is inside a user control from a calling pages page load event handler?
Hopefully this clearly explain the problem I am experiencing.
I have an aspx page.
I also have a user control (ascx). On the user control, there is an asp dropdownlist that is added statically.
My aspx page, dynamically loads the user control in the page load event handler. While in this event handler, I call a method of my user control which has some parameters.
Here is where my problem begins. On drop down list selection, I do a postback. Now, I need to access the selected value of the drop down list in my pages page load event, so that I can send it as an argument when calling my user control method. So my question is, is there any way to access the drop down list selected value from page load of page?
Interface for user control:
public class Workflow
{
public interface iControl
{
System.Web.UI.Control LoadControl();
void SetContext();
int ProcessMe();
}
}
Page with the page load event handler that needs access to the drop down list selected value:
protected void Page_Load(object sender, EventArgs e)
{
Control control = LoadControl("~/UserControls/MyTestControl.ascx");
if (control != null)
{
form1.Controls.Add(control);
var c = (Workflow.iControl)control;
c.SetContext();
}
}
In terms of why this needs to happen, this is some legacy code that I need to work on.
Any help would be greatly appreciated.
Thanks!
See also questions close to this topic
-
Specified method is not supported on setting Frame source
I'm trying to change the source of my frame based on
ListBoxItem
interactions. Here is my code<Style x:Key="NavigationContentStyle" TargetType="Frame"> <Setter Property="Source" Value="/Pages/Dashboard.xaml"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=NavigationMenuListBox, Path=SelectedItem}" Value="Manage"> <Setter Property="Source" Value="/Pages/Manage.xaml"/> </DataTrigger> <DataTrigger Binding="{Binding ElementName=NavigationMenuListBox, Path=SelectedItem}" Value="View"> <Setter Property="Source" Value="/Pages/ViewP.xaml"/> </DataTrigger> <DataTrigger Binding="{Binding ElementName=NavigationMenuListBox, Path=SelectedItem}" Value="Purchase Request"> <Setter Property="Source" Value="/Pages/PRpage.xaml"/> </DataTrigger> </Style.Triggers> </Style>
All four Setter property is throwing same
Specified method is not supported
error. Here is my ListBox<ListBox x:Name="NavigationMenuListBox" Style="{StaticResource NavigationListBoxStyle}" ItemContainerStyle="{DynamicResource NavigationListBoxItemStyle}" ItemTemplate="{DynamicResource NavigationDataTemplate}" ItemsSource="{StaticResource NavigationMenuItems}"/>
and my frame
<Frame Grid.Column="1" NavigationUIVisibility="Hidden" x:Name="MainFrame" Style="{StaticResource NavigationContentStyle}"/>
The application is running exactly as I want. It's just the error. Any idea what's causing the error but also not preventing the application from running?
-
How to parse json and deserialize it to ObservableCollection of a class
I am building a Xamarinforms app that uses a webservice api to fill data in with game of throne cast. The API will fill in the app with the actors name ,picture and stageName.
I am trying to parse json and deserialize it to ObservableCollection of CharacterClass (return Task<ObservableCollection> from this function)
This is the error I get
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.ObjectModel.ObservableCollection`1[GOTapp.CharacterClass]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'characters', line 2, position 16.
namespace GOTapp { public class CharactersManager { public ObservableCollection<CharacterClass> characterList { get; set; } public class LogInResult { public string Name { get; set; } public string cityName { get; set; } public string img { get; set; } public string usrId { get; set; } } public string url = "https://raw.githubusercontent.com/jeffreylancaster/game-of-thrones/master/data/characters.json"; HttpClient client = new HttpClient(); public async Task<ObservableCollection<CharacterClass>> downloadData() { // Get data from provided web service // parse json and deserialize it to ObservableCollection of CharacterClass // return Task<ObservableCollection<CharacterClass>> from this function var json = await client.GetStringAsync(url); characterList = JsonConvert.DeserializeObject<ObservableCollection<CharacterClass>>(json); return characterList; } public void postActor() { var character = new CharacterClass { characterImageThumb = "https://images-na.ssl-images-amazon.com/images/M/MV5BNzI5MDg0ZDAtN2Y2ZC00MzU1LTgyYjQtNTBjYjEzODczZDVhXkEyXkFqcGdeQXVyNTg0Nzg4NTE@._V1._SX100_SY140_.jpg", characterName = "Aeron Greyjoy", actorName = "Michael Feast" }; var content = JsonConvert.SerializeObject(character); client.PostAsync(url, new StringContent(content)); } }
}
Here is the format of the json
{ "characters":[ { "characterName":"Addam Marbrand", "characterLink":"/character/ch0305333/", "actorName":"B.J. Hogg", "actorLink":"/name/nm0389698/" }, { "characterName":"Aegon Targaryen", "houseName":"Targaryen", "royal":true, "parents":[ "Elia Martell", "Rhaegar Targaryen" ], "siblings":[ "Rhaenys Targaryen", "Jon Snow" ], "killedBy":[ "Gregor Clegane" ] } ] }
here is the link for the json data https://raw.githubusercontent.com/jeffreylancaster/game-of-thrones/master/data/characters.json
I would appreciate any form of assistance
-
How can I determine the correct zoom level for Bing Maps when there is only one pushpin?
I add a number of pushpins to a map and then "rightsize" or "right zoom" it so that all the pushpins show but so that the ones on the far edges are barely within the boundaries, like so:
However, if there is only one pushpin (as in the following case with Iowa, which only had the one civil war battle), rather than zero in on that as close as possible, it zooms out all the way to Skylab, like so:
This is the code I use to "right size" the map:
private void RightsizeZoomLevelForAllPushpins() { try { // Set the view so that all pushpins are displayed, with a bit of a margin around them // from https://stackoverflow.com/questions/65779504/how-to-set-the-zoom-level-of-bing-map-to-just-wide-enough-to-display-all-pushpin/65781319#65781319 var map = this.userControl11.myMap; var locations = map.Children.OfType<Pushpin>().Select(x => x.Location); //Margin var w = new Pushpin().Width; var h = new Pushpin().Height; var margin = new Thickness(w / 2, h, w / 2, 0); //Set view map.SetView(locations, margin, 0); currentZoomLevel = Convert.ToInt32(map.ZoomLevel); UncheckAllZoomLevelToolstripMenuItems(); SetZoomMenuItem(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
How can I get a one-pushpin map to not only center, but also zoom in as far as possible?
-
getting prob on reading nested class c#
Hi really need assistance here,
I have 2 classes which i use to read from json i need to save into 2 tables (root and participants) in 1 submission. i will have only 1 root with 1 or many participants. i have no prob saving the root but i have prob reading if i am sending both (root with participants}
[ { "NoIC": "122233243", "Nama": "TEST NAME", ... "Participant": [ { "Nama" : "Participant 1", "Bil" : "1", ... }, { "Nama" : "Participant 2", "Bil" : "1", .... } ] } ] public class Participant { public string ref_no { get; set; } public string Nama { get; set; } public string Bil { get; set; } public string Price { get; set; } public string RequestedPlace { get; set; } public string RequestedExe { get; set; } public string RequestedDate { get; set; } public string Type { get; set; } } public class Root { public string NoIC { get; set; } public string Nama { get; set; } public string HPNo { get; set; } public string Email { get; set; } public string Type { get; set; } public string RegisterBy { get; set; } public List<Participant> Participant { get; set; } } public string RegisterApplication([FromBody] Root register, Participant participants) { try { using (MySqlConnection sql = new MySqlConnection(_connectionString)) { using (MySqlCommand cmd = new MySqlCommand("GetInsertApplication", sql)) { sql.Open(); cmd.CommandType = System.Data.CommandType.StoredProcedure; // cmd.Parameters.AddWithValue("@refNo", register.RefNo); cmd.Parameters.AddWithValue("@NoIC", register.NoIC); cmd.Parameters.AddWithValue("@Nama", register.Nama.ToUpper()); cmd.Parameters.AddWithValue("@NoFonHp", register.HPNo); cmd.Parameters.AddWithValue("@Email", register.Email); cmd.Parameters.AddWithValue("@refType", register.Type); cmd.Parameters.AddWithValue("@RegisterBy", register.RegisterBy); ...... ref_no = refnoParameter.Value.ToString(); //will pass this refno to child/participant
my prob is here. i need to read the child (1 Root can have more than 1 participant)
List<Participant> participants = new List<Participant>(); using (MySqlCommand cmd2 = new MySqlCommand("GetInsertParticipant", sql)) { cmd2.Parameters.AddWithValue("@ref_no", ref_no); cmd2.Parameters.AddWithValue("@Nama", participant.Nama.ToUpper()); cmd2.Parameters.AddWithValue("@Bil", participant.Bil); cmd2.Parameters.AddWithValue("@Price", participant.Price); cmd2.Parameters.AddWithValue("@RequestedPlace", participant.RequestedPlace); cmd2.Parameters.AddWithValue("@RequestedExe", participant.RequestedExe); cmd2.Parameters.AddWithValue("@RequestedDate", participant.RequestedDate); cmd2.Parameters.AddWithValue("@Type", participant.Type); cmd2.Connection.Open(); cmd2.CommandType = CommandType.Text; cmd2.ExecuteNonQuery();
}}}}}
anybody please, i stuck here for few days and i really need your help/opinion. thaks in advanced
-
How do I insert input from form to database?
My model looks like this:
public class Customer { public int CustomerId { get; set; } [Required(ErrorMessage = "Please enter a valid first name")] public string FirstName { get; set; } [Required(ErrorMessage = "Please enter a valid last name")] public string LastName { get; set; } [Required(ErrorMessage = "Please enter a valid address")] public string Address { get; set; } public string Email { get; set; } [Required(ErrorMessage = "Please enter a valid city")] public string City { get; set; } public string Phone { get; set; } [Range(1, 5, ErrorMessage = "Please enter a valid country")] public int CountryId { get; set; } public Country Country { get; set; } [Required(ErrorMessage = "Please enter a valid state")] public string State { get; set; } [Required(ErrorMessage = "Please enter a valid postal code")] public string PostalCode { get; set; } public string fullname => FirstName + LastName; }
My controller looks like this:
public class CustomerController : Controller { private CustomerContext context { get; set; } public CustomerController(CustomerContext ctx) { context = ctx; } public IActionResult List() { var customers = context.Customers.ToList(); return View(customers); } [HttpGet] public IActionResult Add() { ViewBag.Action = "Add"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View("Edit", new Customer()); } [HttpGet] public IActionResult Edit(int id) { ViewBag.Action = "Edit"; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); var customer = context.Customers .Include(c => c.Country) .FirstOrDefault(c => c.CustomerId == id); return View(customer); } [HttpPost] public IActionResult Edit(Customer customer) { string action = (customer.CustomerId == 0) ? "Add" : "Edit"; if (ModelState.IsValid) { if (action == "Add") { context.Customers.Add(customer); } else { context.Customers.Update(customer); } context.SaveChanges(); return RedirectToAction("List", "Customer"); } else { ViewBag.Action = action; ViewBag.Countries = context.Countries.OrderBy(c => c.Name).ToList(); return View(customer); } }
I also have a DbContext file with data i created to test other things:
public class CustomerContext : DbContext { public CustomerContext(DbContextOptions<CustomerContext> options) :base(options) { } public DbSet<Customer> Customers { get; set; } public DbSet<Country> Countries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Country>().HasData( new Country { CountryId = 1, Name = "Canada"}, new Country { CountryId = 2, Name = "United States"}, new Country { CountryId = 3, Name = "United Kingdom" }, new Country { CountryId = 4, Name = "Mexico" }, new Country { CountryId = 5, Name = "Russia" } ); modelBuilder.Entity<Customer>().HasData( new Customer { CustomerId = 1, FirstName = "Bruce", LastName = "Wayne", Phone = "416-123-4567", Email = "bruce.wayne@gmail.com", CountryId = 1, Address = "123 sesame street", City = "Toronto", PostalCode = "L812A", State = "Ontario" } ); }
I already did the add-migration and updated my database via the package manager console. I created a form in the view that looks like this:
Cancel<form method="post" asp-action="Add"> <div asp-validation-summary="All"> <div> <label asp-for="FirstName">First Name</label> <input type="text" name="FirstName" asp-for="FirstName" /> </div> <div> <label asp-for="LastName">Last Name</label> <input type="text" name="LastName" asp-for="LastName" /> </div> <div> <label asp-for="Address">Address</label> <input type="text" name="Address" asp-for="Address" /> </div> <div> <label asp-for="City">City</label> <input type="text" name="City" asp-for="City" /> </div> <div> <label asp-for="State">State</label> <input type="text" name="State" asp-for="State" /> </div> <div> <label asp-for="PostalCode">Postal Code</label> <input type="text" name="Postal Code" asp-for="PostalCode" /> </div> <div> <label asp-for="CountryId">Country</label> <select name="Country" asp-for="CountryId"> @foreach (Country country in ViewBag.Countries) { <option value="@country.CountryId">@country.Name</option> } </select> </div> <div> <label asp-for="Email">Email</label> <input type="text" name="Email" asp-for="Email" /> </div> <div> <label asp-for="Phone">Phone</label> <input type="text" name="Phone" asp-for="Phone" /> </div> <input type="hidden" asp-for="CustomerId" /> </div> <button type="submit" value="Save" asp-controller="Customer" asp-action="List">Save</button>
I've tried looking up multiple different solutions to solve my issue but I cant seem to figure out how to solve it. If someone could help me that would be much appreciated. thanks in advance.
-
Submit button doenst work with script asp.net mvc5
I have a maybe simple problem but I don`t have that much experience with scripts:
I have this Skript in my _Layout.cshtml:
<script> $('button').click(function () { $(this).prop('disabled', true); }); </script>
and one of my views:
@using (Html.BeginForm("Create", "Home", FormMethod.Post, null)) { @Html.AntiForgeryToken() <div class="mt-5 d-flex flex-row"> <textarea class="form-control" name="TextArea"></textarea> <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button> </div> }
This form works great without the script, but for any reason with the script it doesn`t work.
I placed the script in the _layout.cshtml because I want to have it for all buttons in my asp.net page.
After click on the button the button is disabled - as I wish - but the action result "Create" in the HomeController will not called.
I think I need to extend the script but can someone help me how to do it?
Thanks all
-
How to generate at least include one negative number
The way i generate is all random number, even mostly include negative number. But how to generate this random number which MUST include at least one negative number?
protected void Button1_Click(object sender, EventArgs e) { var textBoxes = new List<TextBox> { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 }; var rand = new Random(Guid.NewGuid().GetHashCode()); foreach (var textBox in textBoxes) textBox.Text = rand.Next(-100, 100).ToString(); }
-
Validation Summary Not Displaying (C# ASP.NET 4.5)
I have a an ASP.NET web form that needs to valid user input. However, upon entering invalid-user input the validation summary is not displaying. The weird thing was that it was working for a period of time and then now it doesn't show at all. Here is my code.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %> <!DOCTYPE html> <html> <head> <title>Coding Club Registration</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Coding Club Registration Form</h1> <form runat="server" defaultbutton="Submit"> <div> <asp:Label ID="NameLabel" runat="server" Text="Your Name:" AssociatedControlID="NameTextBox" AccessKey="N"></asp:Label> <asp:TextBox ID="NameTextBox" runat="server" Columns="30" MaxLength="30"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="NameTextBox" CssClass="error" ErrorMessage="Name Required"><span>*</span></asp:RequiredFieldValidator> <br /><br /> <asp:Label ID="EmailLabel" runat="server" Text="Your Email:" AssociatedControlID="EmailTextBox" AccessKey="N"></asp:Label> <asp:TextBox ID="EmailTextBox" runat="server" Columns="30" MaxLength="30"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="EmailTextBox" CssClass="error" Display="Dynamic" ErrorMessage="Email Required"><span>*</span></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="EmailTextBox" CssClass="error" Display="Dynamic" ErrorMessage="Invalid Email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator> <br /><br /> <asp:Label ID="PhoneLabel" runat="server" Text="Your Phone:" AssociatedControlID="PhoneTextBox" AccessKey="N"></asp:Label> <asp:TextBox ID="PhoneTextBox" runat="server" Columns="30" MaxLength="30"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="PhoneTextBox" CssClass="error" Display="Dynamic" ErrorMessage="Phone Required"><span>*</span></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="PhoneTextBox" CssClass="error" Display="Dynamic" ErrorMessage="Invalid Phone" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">*</asp:RegularExpressionValidator> <br /><br /> <asp:Button ID="Submit" runat="server" Text="Submit Form" AccessKey="S" onclick="SubmitButton_Click" /> <asp:Button ID="Clear" runat="server" Text="Clear Form" AccessKey="C" onclick="ClearButton_Click" CausesValidation="False" /> <br /><br /> <div class="container"> <asp:Label ID="Result" runat="server" Text="" Visible="false"></asp:Label> </div> </div> <asp:ValidationSummary ID="Errors" runat="server" ForeColor="Red" /> </form> </body> </html>
protected void SubmitButton_Click(object sender, EventArgs e) { if (Page.IsValid) { // Add form results to result label string newText = "<h3>The Information Entered</h3>"; newText += "<p>Name: " + NameTextBox.Text + "</p>"; newText += "<p>Email: " + EmailTextBox.Text + "</p>"; newText += "<p>Phone: " + PhoneTextBox.Text + "</p>"; Result.Text = newText; // Set result lable visibility to true Result.Visible = true; } } protected void ClearButton_Click(object sender, EventArgs e) { // Clear form fields NameTextBox.Text = ""; EmailTextBox.Text = ""; PhoneTextBox.Text = ""; // Remove result visibility Result.Visible = false; // Errors.Visible = false; } }
-
How to get the sum of the numbers from the list
After i generate a group of random number from -100 to 100, how do i sum up all the number?
protected void Button1_Click(object sender, EventArgs e) { var textBoxes = new List<TextBox> { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 }; var rand = new Random(Guid.NewGuid().GetHashCode()); foreach (var textBox in textBoxes) textBox.Text = rand.Next(-100, 100).ToString(); }