ASP.Net My Updated Value From Drop Down List Doesn't Update/Display - html

I have a 4 page ASP.NET form which is storing data in the session. A button on my 3rd page clears the session. All this is working fine but I'm having a problem updating a value on my confirmation page as it retains/displays my initial selected value and i cant figure out why.
1st Page HTML With DropDownList
<asp:DropDownList ID="ddlInnoc" runat="server" class="form-control">
<asp:ListItem Value="0">- - Please Select - -</asp:ListItem>
<asp:ListItem Value="Male">Male</asp:ListItem>
<asp:ListItem Value="Female">Female</asp:ListItem>
</asp:DropDownList>
1st Page Code Behind Which Re-displays Selected Value
protected void Page_Load(object sender, EventArgs e)
{
txtData1.Focus();
if (txtData1.Text == string.Empty && Session["pg1input"] != null)
{
txtData1.Text = Session["pg1input"].ToString();
}
if (Session["pg1dd"] != null)
{
ddlInnoc.SelectedValue = Session["pg1dd"].ToString();
}
//if (Session["pg1dd"].ToString() == "")
//{
// ddlInnoc.SelectedValue = Session["pg1dd"].ToString();
//}
}
protected void pg1button_Click(object sender, EventArgs e)
{
Session["pg1input"] = txtData1.Text;
Session["pg1dd"] = ddlInnoc.SelectedItem;
Response.Redirect("/Session/pg2.aspx");
}
Page 3 HTML Code
<div class="form-group">
<div class="col-xs-12">
<asp:Label ID="Label1" class="col-md-2 control-label" runat="server" Text="Name:"></asp:Label>
<div class="col-md-3 form-control-static">
<%=Session["pg1input"] %>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<asp:Label ID="Label2" class="col-md-2 control-label" runat="server" Text="Sex:"></asp:Label>
<div class="col-md-3 form-control-static">
<%=Session["pg1dd"] %>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-offset-4 col-xs-12">
<asp:LinkButton ID="pg1EditButton" runat="server" OnClick="pg1EditButton_Click" CssClass="btn btn-default">
<span aria-hidden="true" class="glyphicon glyphicon-pencil"></span> Edit
</asp:LinkButton>
</div>
</div>
Page 3 Edit Button Code Behind
protected void pg1EditButton_Click(object sender, EventArgs e)
{
Response.Redirect("/Session/pg1.aspx");
}
I suspect that its something to do with the code behind on my page 1 as all the other fields/radio buttons on the other pages retrieves and displays the updated value on my 3rd page.

You are setting it back to the value in your session on postback.
Add this to your Page_Load.
if (!IsPostBack)
{
//set values from session
}

Fix is
if (!IsPostBack)
{
if (ddlInnoc.SelectedValue != "0" && Session["pg1dd"] != null)
{
ddlInnoc.SelectedValue = Session["pg1dd"].ToString();
}
}

Related

Modal ajax.form validation ASP.NET MVC, error message not showing, modal not closing after succesful submit

i'm new to the ASP.net and i get easilly confused when jquery and Ajax get in the middle of a code.
I have a popup bootstrap Modal that show when i click on a button, the Modal contains an Ajax.form that allows me to create projects, i'm using HTML.validation to check if my form is filled correctly. I have two main problems :
When I enter valid informations in my form and i submit the form, the project is created succesfully but the Modal doesn't close automaticlly.
When i enter non-valid informations when i submit no message error apear, nonetheless when I close the modal and open it again, the errors apear.
I need your help to :
Close the modal once the submit form is valid.
Have the error message show in my modal form.
*This is a part of my main view :
enter code here
<!--validation script -->
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<!-- Button trigger modal -->
<div>
<div>
<a class="btn btn-red ms-auto my-auto h-50"
href="#Url.Action("createProject", "ProjectSelection")" title="Nouveau projet"
data-bs-toggle="modal" data-bs-target="#Modal_NewProject"
ajax-target-id="Body_NewProject" data-bs-loader="Loader_NewProject">
<i class="feather-16" data-feather="plus"></i>
Créer projet
</a>
</div>
</div>
<br />
<!-- Modal View -->
<div class="modal fade" id="Modal_NewProject" tabindex="-1"
aria-labelledby="Label_NewProject" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Label_NewProject">
Créer un Projet</h5>
<button type="button" class="btn-close"
data-bs-dismiss="modal" aria-label="Close"></button>
</div>
#using (Ajax.BeginForm("createProjectPost",
"ProjectSelection", new AjaxOptions { HttpMethod = "POST",
UpdateTargetId = "Body_NewProject" }, new { id = "projectForm" }))
{
<div id="Body_NewProject">
<div class="spinner-border" role="status"
id="Loader_NewProject">
<span class="visually-hidden">Loading...</span>
</div>
<!-- partial view "createProject" -->
</div>
}
</div>
</div>
</div>
<!---->
*And this is my partial view that containts the elements of the form
<div class="modal-body" id="frmProject">
<div class="input-group mb-3" id="">
#Html.DropDownListFor(m => m.Project.Domain,
new SelectList(Model.Domains, "IdDomain", "Name"),"Selectionner un domaine",
new { #class = "w-100", #id = "DomainSelection" })
#Html.ValidationMessageFor(m => m.Project.Domain, null,
new { style = "color: red;" })
</div>
<div class="input-group mb-3 mb-3 " id="teamSelection">
#Html.DropDownListFor(m => m.Project.Teams,
new SelectList(Model.Teams.Select(teamElement => teamElement.Name).ToList()),
"Selectionner une équipe", new { #class = "w-100" })
#Html.ValidationMessageFor(m => m.Project.Teams, null,
new { style = "color: red;" })
</div>
<div class="form-floating mb-3">
<input class="form-control " data-val-required="Le champ Projet est requis."
id="Project.Name" name="Project.Name" type="text" value="">
<label for="Project.Name" class="">Nom du projet</label>
#Html.ValidationMessageFor(m => m.Project.Name, null,
new { style = "color: red;" })
</div>
</div>
<div class="modal-footer mb-0">
<div class="panel-footer">
<button class="btn btn-secondary" data-bs-dismiss="modal"
type="button">Annuler</button>
<button type="submit" form="projectForm"
class="btn btn-red">Valider</button>
<div class="col-xs-10" id="lblstatus"></div>
</div>
</div>
*This is my Controller code
public ActionResult createProject()
{
//initialization code
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
[HandleError]
public ActionResult createProjectPost(Project project)
{
#region Variable verification
if (!ModelState.IsValid)
{
Session["Error"] = true;
if (project.Domain == null)
{
Session["DomainError"] = true;
}
if (project.Teams == null)
{
Session["TeamError"] = true;
}
if (project.Name == null)
{
Session["NameError"] = true;
}
ViewData["project"] = "create";
//return View("ProjectSelectionPage");
return PartialView(project);
}
#endregion
#region Initialisation
//initilization code
#endregion
#region Check possible copy of the project
if (projectDB.Exist(project.Name))
{
//Check that this project doesn't exist in the database
//Create a session variable that will trigger an error message
Session["Error"] = true;
Session["NameCopy"] = true;
ViewData["project"] = "create";
return PartialView(project);
}
#endregion
#region Project to database and generate name
//Add the project to the database
#endregion
return PartialView();
}
It's been several days since i'm searching for an answer, i either missed one or didn't use it correctly.
enter image description here
Thank you

EditForm in Blazor app have multiple submit buttons

I have a simple Blazor Editform where i have multiple buttons with different navigations & toast notifications. I have OnValidSubmit attached to Editform. Now the validations are working for all the buttons. I have added onclick() to trigger button functions but I want onclick to be triggered only if user has entered all the details. Hope I have explained well. Please let me know for additional input.
Current output for Forward or Next buttons are : if No values entered -> Correct validation(asked to fill in details) -> forward notification displayed.
Expected output :
if No values entered -> Correct validation(asked to fill in details).
if All values entered -> Correct validation -> forward notification displayed.
Here is some code:
<EditForm EditContext="#editContext" OnValidSubmit="HandleValidSubmit" #onreset="HandleReset">
<DataAnnotationsValidator />
<div class="form-row">
<div class="form-group col">
<label>Role</label><br />
<InputRadioGroup #bind-Value="model.Role" class="form-control">
#foreach (var option in rdOptions)
{
<InputRadio Value="option" /> #option
<text> </text>
}
</InputRadioGroup>
<ValidationMessage For="#(() => model.Role)" />
</div>
<div class="form-group col">
<label>Company Name</label>
<InputSelect id="txtCompanyName" class="form-control" #bind-Value="#model.CompanyName">
<option selected value="-1">-Select-</option>
<option value="CompanyName1">CompanyName1</option>
<option value="CompanyName2">CompanyName2</option>
</InputSelect>
<ValidationMessage For="#(() => model.CompanyName)" />
</div>
</div>
<div class="form-row">
<div class="text-left col-3">
<button type="submit" class="btn btn-primary btn-success">Save</button>
</div>
<div class="text-right col-3">
<button type="submit" class="btn btn-primary" #onclick="#Forward">Forward</button>
</div>
<div class="text-right col-3">
<button type="submit" class="btn btn-primary" #onclick="#Review">Next</button>
</div>
<div class="text-right col-3">
<button type="reset" class="btn btn-secondary">Clear</button>
</div>
</div>
</EditForm>
code section:
#code {
private Model model = new Model();
private EditContext editContext;
List<Model> models = new();
protected override void OnInitialized()
{
editContext = new EditContext(model);
}
private void HandleValidSubmit()
{
var modelJson = JsonSerializer.Serialize(model, new JsonSerializerOptions { WriteIndented = true });
JSRuntime.InvokeVoidAsync("alert", $"SUCCESS!! :-)\n\n{modelJson}");
toastService.ShowSuccess("saved successfully!");
}
private void Forward()
{
toastService.ShowInfo("Forwarded!!");
}
private void Review()
{
toastService.ShowInfo("Review!!");
}
private void HandleReset()
{
model = new Model();
editContext = new EditContext(model);
}
}
Change type="submit" to type="button"
Except maybe for the Save button.
You can do validation manually in your button event handlers and then not use the EditForm OnValidSubmit, and set the button types to button.
...
if (editContext.Validate())
go
else
alert
...
FYI - The relevant bit of code from EditForm looks like this:
private async Task HandleSubmitAsync()
{
Debug.Assert(_editContext != null);
if (OnSubmit.HasDelegate)
{
// When using OnSubmit, the developer takes control of the validation lifecycle
await OnSubmit.InvokeAsync(_editContext);
}
else
{
// Otherwise, the system implicitly runs validation on form submission
var isValid = _editContext.Validate(); // This will likely become ValidateAsync later
if (isValid && OnValidSubmit.HasDelegate)
{
await OnValidSubmit.InvokeAsync(_editContext);
}
if (!isValid && OnInvalidSubmit.HasDelegate)
{
await OnInvalidSubmit.InvokeAsync(_editContext);
}
}
}
In my opinion you will need to use JavaScript to check the inputs were filled or not and based on that you can disable or enable the submit button

Unable to use html controls from code behind

I am using html tags and I have written some code on code behind but it is not picking the values given to id. Infact it says the 'FileUpload1' does not exist in the current context. I do not want to use asp controls at all. I have heard adding runat = "server" does the thing but still cannot find the id's. What am I doing wrong?
<div id="mainContent">
<div class="column" id="colFull">
<div class="contentSection">
<div id="progress" style="display: none">
<img alt="Loading .." src="../../../Images/ajax.gif" />
</div>
<table width="100%">
<tr>
<td class="label" style="width:15%">
Upload File
</td>
<td class="description" >
<input type="file" id="FileUpload1" runat="server"
class="largeTextField" onclick="Upload" multiple="multiple"
style="width:260px;"/>
<input type="button" id="btnUpload"
runat="server" value="Upload" />
</td>
</tr>
</table>
mycodebehind:
public partial class PgPracFileUploader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
It says FileUpload1 does not exist in the current context.
Try to change:
<input type="file" id="FieUpload1" runat="server" class="largeTextField" onclick="Upload" multiple="multiple" style="width:260px;"/>
to
Id Must be same as you are using in the .cs page
\/\/\/\/
<input type="file" ID="FileUpload1" runat="server" class="largeTextField" onclick="Upload" multiple="multiple" style="width:260px;"/>
As stated here your id attribute is case sensitive so you are using id then the server will just serve it up as it is in your page, but if you used ID then the server will be serve that control as a asp.net control.

Partial page updating using update panel

I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?
Set AutoPostBack= true for the first ddl
U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}

updatepanel does not trigger repeater itemcommand

I just want to trigger the LinkButton in a repeater which has a OnItemCommand. But the page do post back. Here is my code:
<asp:UpdatePanel ID="recommendedAdvertsUpPnl" runat="server">
<ContentTemplate>
<div class="tagList">
<asp:Label ID="lbListBookType" runat="server"></asp:Label>
<asp:Repeater ID="rpRecommendedAdvertFacultyList" runat="server" OnItemDataBound="rpRecommendedAdvertFacultyList_ItemDataBound" OnItemCommand="rpRecommendedAdvertFacultyList_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnAdvertFaculty" runat="server" CommandArgument='<%#Eval("facultyId") %>' CommandName="selectFaculty" CssClass="advertFacultySelection"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
</div>
<div class="RecommendedAdverts_List">
<asp:Repeater ID="rpRecommendedAdvertList" runat="server" OnItemDataBound="rpRecommendedAdvertList_ItemDataBound">
<HeaderTemplate>
<ul class="content_recommended">
</HeaderTemplate>
<ItemTemplate>
<%# Container.ItemIndex % 4 == 0 ? "<li><div class=advertContainer>": String.Empty%>
<div class="advertPanel">
<div class="rAdvPanel">
<div class="advertPic"><asp:Panel ID="pnlRecAdvertPic" runat="server"></asp:Panel></div>
<div class="advertInfoPanel">
<%#Eval("Book.Name")%> <br />
<%#Eval("Book.Authors")%><br />
<%#Eval("Price")%> TL<br />
</div>
</div>
</div>
<%# Container.ItemIndex % 4 == 3 ? "</div></li>": String.Empty%>
</ItemTemplate>
<FooterTemplate>
</div></li>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rpRecommendedAdvertFacultyList" EventName="ItemCommand" />
</Triggers>
</asp:UpdatePanel>
There is no problem except for triggering. Here is the my server side code:
protected void rpRecommendedAdvertFacultyList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
AdvertFacultyInfo item = (AdvertFacultyInfo)e.Item.DataItem;
LinkButton lbtnAdvertFaculty = (LinkButton)e.Item.FindControl("lbtnAdvertFaculty");
lbtnAdvertFaculty.Text = item.Faculty.name;
}
}
protected void rpRecommendedAdvertFacultyList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "selectFaculty":
List<AdvertFacultyInfo> advFacultyInfoList = EntitiyProvider.GetAdvertFacultyInfoListByFacultyId(Convert.ToInt32(e.CommandArgument));
List<Advert> selectedList = new List<Advert>();
foreach (AdvertFacultyInfo item in advFacultyInfoList)
{
Advert currentAdv = this.recommendedAdvertList.FirstOrDefault(i => i.id == item.advertId);
if ( currentAdv != null)
{
selectedList.Add(currentAdv);
}
}
rpRecommendedAdvertList.DataSource = selectedList;
rpRecommendedAdvertList.DataBind();
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script type='text/javascript'>$('.content_recommended').quickPager()</script>", false);
break;
default:
break;
}
}
I have also tried this code: But it gives error like lbtnAdvertFaculty could'nt find
<asp:AsyncPostBackTrigger ControlID="lbtnAdvertFaculty" EventName="Click" />
I have researched a lot of document written about this problem but I could not find useful examples and solution.
Best Regards.
try putting ClientIDMode="AutoID" to #page directive