CalendarExtender loose his value on postback - postback

Here is the code of my date selecting control.
When the page containing the control is submitted AFTER the Page_Load and link button click events passed, tb is reset to it is initial value (which is today)
<div class="ui-form-text">
<div>
<asp:TextBox ID="tb" runat="server" autocomplete="off"></asp:TextBox></div>
</div>
<ajaxToolkit:CalendarExtender ID="ce" runat="server" TargetControlID="tb" Format="dd/MM/yyyy"
CssClass="calendar" EnableViewState="true">
</ajaxToolkit:CalendarExtender>
<ajaxToolkit:MaskedEditExtender ID="mee" runat="server" TargetControlID="tb" Enabled="true"
Mask="99\/99\/9999" ClearMaskOnLostFocus="false" EnableViewState="true">
</ajaxToolkit:MaskedEditExtender>
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="tb" Display="Dynamic"
ErrorMessage="Невалидна дата" Operator="DataTypeCheck" Type="Date" ForeColor="Red">
</asp:CompareValidator>
<asp:RangeValidator ID="rv" runat="server" ControlToValidate="tb" Type="Date">
</asp:RangeValidator>

I am having the same problem myself and the only solution (well, workaround) I could find was this:
ASP.NET Ajax CalendarExtender will not update SelectedDate value

I hope this can help you, this worked for me.
String tmp_;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Request[txtCalendarExtender.UniqueID] != null)
{
if (Request[txtCalendarExtender.UniqueID].Length > 0)
{
this.tmp_ = Request[txtCalendarExtender.UniqueID];
}
}
}
}

Related

Checkbox Form Submit trigger Logout in Identity EntityFramework on _loginpartial-C# asp.net MVC

I have a checkbox(justdoit) on asp.net MVC create view. If checkbox checked, it submits#onclick = "document.forms[0].submit() value and according to that, if else condition disable or enable other dropbox form("Status) in view.It was working without problem. After I integrated authorization to page(Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.10), I added _loginpartial to _layout.cshtml page. Then I log in page with authorised user and enter create item page,when I check to checkbox(onlick submit works), log out is trigered and I log out the site and find myself on the indexpage. After that I tried to create item without login, it works without problem. Therefore I think checkbox submit trigger the logout.(Project.Identity.Pages.Account.LogoutModel: Information: User logged out.) How Can I solve that problem?
Thank you for answer in advance
Code in the view:
#Html.CheckBox("Justdoit", false, new { #onclick = "document.forms[0].submit();" })
Justdoit
<br />
#if(Convert.ToBoolean(ViewBag.Justdoit))
{
<div class="form-group">
<label asp-for="Status" class="control-label">Status (Choose One)</label>
<select asp-for="Status" class="form-control" id="Status" disabled>
<option>Completed</option>
</select>
<span asp-validation-for="Status" class="text-danger"></span>
</div>
}
else
{
<div class="form-group">
<label asp-for="Status" class="control-label">Status (Choose One)</label>
<select asp-for="Status" class="form-control" id="Status" >
<option>Completed</option>
<option>Plan</option>
<option>Do</option>
<option>Study</option>
<option>Act</option>
</select>
<span asp-validation-for="Status" class="text-danger"></span>
</div>
}
</td>
Code in the _loginpartial
<li class="nav-item">
<form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Action("Index", "Home", new { area = "" })">
<button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button>
</form>
</li>
Item controller- It logs out before calling ViewBag.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult>Create(bool Justdoit,[Bind("Id,Title,Description,MainBody,Team,Owner,StartDate,Status,Justdoit,Category")] Suggestion suggestion)
{
ViewBag.Justdoit = Justdoit;
if (ModelState.IsValid)
{
_context.Add(suggestion);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(suggestion);
}
Logout model View
#page
#model LogoutModel
#{
ViewData["Title"] = "Log out";
}
<header>
<h1>#ViewData["Title"]</h1>
#{
if (User.Identity.IsAuthenticated)
{
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="#Url.Page("/", new { area = "" })" method="post">
<button type="submit" class="nav-link btn btn-link text-dark">Click here to Logout</button>
</form>
}
else
{
<p>You have successfully logged out of the application.</p>
}
}
</header>
Logout model cshtml.cs file
public class LogoutModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
// This needs to be a redirect so that the browser performs a new
// request and the identity for the user gets updated.
return RedirectToPage();
}
}
}
Enable or Disable form based on Condition in ASP.Net MVC. Condition is created by clicking the checkbox. I want to use that feature on the authorized page.

MVC dropdown index change

I got a requirement can any one please suggest me ideas if possible with sample
I have a dropdown and beneath i have couple of checkboxes...
For each dropdown item user can select checkboxes.., if user change index of dropdown previous dropdown index and checkbox should maintain in session and new index item can select boxes....
All together we need to post to server...
for eg; dropdown list contains apple,samsung,motorola,htc
checkboxes contain 3G,LTE,Speed,Bandwdth..
once apple is selected he selected values 3g and LTE. and again user selected samsung in dropdown and he selected check boxes speed and lTE.
While posting to server i need to send both list like
apple 3G
apple LTE
Samsung Speed
Samsung LTE
Could any one please suggest some ideas and example
Rather than using Dropdown List you can use div with labels and checkboxes and use jQuery to post data.
You can use jQuery plugin in your case. Here is a good example http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/
I am sure there will be many other way to do this, and i think this will help you.
In aspx page:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value="-1">Select a Device</asp:ListItem>
<asp:ListItem>Apple</asp:ListItem>
<asp:ListItem>Samsung</asp:ListItem>
<asp:ListItem>Nokia</asp:ListItem>
<asp:ListItem>HTC</asp:ListItem>
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>3G</asp:ListItem>
<asp:ListItem>LTE</asp:ListItem>
<asp:ListItem>Speed</asp:ListItem>
<asp:ListItem>Bandwidth</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button ID="ButtonSubmit" runat="server" OnClick="ButtonSubmit_Click" Text="Submit" />
<asp:Button ID="ButtonSave" runat="server" OnClick="ButtonSave_Click" Text="Save Data" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Clear First ListBox" />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="88px" SelectionMode="Multiple" Width="208px"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server" Height="88px" SelectionMode="Multiple" Width="208px"></asp:ListBox>
</div>
</form>
and in code behind file paste this,
protected void Page_Load(object sender, EventArgs e)
{
}
public void LoadDataToListBox(string list1)
{
ListBox1.Items.Add(list1);
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (ListBox1.Items.Count != 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListBox2.Items.Add(ListBox1.Items[i]);
}
}
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if(DropDownList1.SelectedValue!="-1")
{
string item1 = "You'r device is " + DropDownList1.SelectedValue;
LoadDataToListBox(item1);
}
foreach (ListItem li in CheckBoxList1.Items)
{
if(li.Selected)
{
LoadDataToListBox("You Choose " + li.Text);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
}

MVC textbox list

I want my mvc to act the same way as my classic asp example. My classic asp example is simple.
I can add as many values to list box with np. my mvc only allows one then replace each value everytime I add one. How can I get my mvc to work like Classic asp.net.
Classic Asp.net
aspx.
<asp:textbox runat="server" ID="StoreToAdd" ></asp:textbox>
<asp:Button ID="btnAddStore" runat="server" Text="Add" OnClick="btnAddStore_Click1" />
backend c#
protected void btnAddStore_Click1(object sender, EventArgs e)
{
lstStores.Items.Add(StoreToAdd.Text);
StoreToAdd.Text = "";
}
MVC view
#using(Html.BeginForm("Index", "Home")) {
#Html.TextBoxFor(mod => mod.StoreToAdd, new { Style = "height:20px; " })
<div align="center">
<input type="submit" name="addS" id="addS" value="Add"
/></div>
#Html.ListBoxFor(model => model.lstStores, new
new MultiSelectList(Model.lstStores),
new { style = "width:225px;height:255px" })
}
Controller
[HttpPost]
public ActionResult Index(HomeModel model)
{
model.lstStores = new List<string>();
model.lstStores.Add(model.StoreToAdd);
return View(model);
}
Your doing this in your controller:
model.LstStores = new List<string>();
Wouldn't you expect that to reset your list each time?
Perhaps you could check if the list has already been instantiated first, and just add the new item if it has:
[HttpPost]
public ActionResult Index(HomeModel model)
{
if (model.lstStores != null)
{
model.lstStores.Add(model.StoreToAdd);
}
else
{
model.lstStores = new List<string>();
model.lstStores.Add(model.StoreToAdd);
}
return View(model);
}

Achieving UpdatePanel-Functionality in MVC

I got a Label, a Textbox and a Button on a Page.
When entering a Value into the Textbox I want to display something on the Label. The Button also gets that information and runs some code.
In ASP.NET I would just put an Ajax UpdatePanel around those three controls, add two events on TextBox. TextChange and Button.Click and react on Postback.
How do I do this in MVC?
Life cycle of MVC and webforms both are different.
MVC is not about server controls.... viewstate... no page life cycle events in web form...
What is the 'page lifecycle' of an ASP.NET MVC page, compared to ASP.NET WebForms?
hope this helps..
Now coming to your point.
if you want to display something in the Label while entering a Value into the Textbox you have to use client side script see example below
javascript
<script type="text/javascript" language="javascript">
function textCounter(field, field2, maxlimit) {
var countfield = document.getElementById(field2);
if (field.value.length > maxlimit) {
field.value = field.value.substring(0, maxlimit);
return false;
} else {
countfield.value = maxlimit - field.value.length;
}
}
</script>
Your Html page
<%using (Html.BeginForm("Index", "Account", FormMethod.Post)) // here index is a ActionName, Account is a controller name
{%>
<input type="text" name="Message" onkeyup="textCounter(this,'counter',208)"/>
<label><input disabled maxlength="3" size="3" value="208" id="counter" /></label>
<input type="submit" value="Send" />
<%}%>
Here
textCounter() function on keyup event in textbox will display value in label,
submit button will submit form, calling action "index" on controller "Account",see below how action act
public class AccountController : Controller
{
[HttpPost]
public ActionResult index(FormCollection result)
{
string TextBoxValue=result["Message"];
return view("yourviewname");
}
}
i hope this example may help you..

SqlDataSource custom paging

I need use sqldatasource(stored proc) to bind a gridview.
<asp:GridView ID="gvBC" runat="server" AutoGenerateColumns="False" ShowFooter="True" AllowSorting="True" AllowPaging="True" pageSize ="3" DataSourceID="dsBCSearch">
<Columns>
<asp:BoundField DataField="ContactID" HeaderText="ContactID" Visible="false"/>
<asp:BoundField DataField="BldgNum" HeaderText="Bldg#" SortExpression="BldgNum" />
</Columns>
<EmptyDataTemplate> No Building Coordinator Found. </EmptyDataTemplate>
<EmptyDataRowStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:SqlDataSource ID="dsBCSearch" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnStr %>" SelectCommand="GetBC" SelectCommandType="StoredProcedure"
SortParameterName="SortExpression" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
LoadBC();
}
protected void LoadBC()
{
dsBCSearch.SelectCommand = "GetBCwP";
dsBCSearch.SelectParameters.Clear();
dsBCSearch.SelectParameters.Add("LName", this.txtLNAme.Text.Trim());
dsBCSearch.SelectParameters.Add("Active", this.chkActive.Checked.ToString());
//dsBCSearch.SelectParameters.Add("sortExpression", this.gvBC.SortExpression);
dsBCSearch.SelectParameters.Add("startRowIndex", this.gvBC.PageIndex.ToString());
dsBCSearch.SelectParameters.Add("maximumRows", this.gvBC.PageSize.ToString());
this.gvBC.DataBind();
}
Now just render first page (3 records) and in footer no number showing up. HOw can I add paging to footer?
Thanks
sqldatasource is not good for custom paging. I have to add another pager part and like old asp page, to manually write the code.
But objectdatasource is much easy for this. It will have some parameter like StartRowIndexParameterName MaximumRowsParameterName SortParameterName SelectCountMethod. It will auto pass to data souce

Resources