ASP.NET : Textbox OnTextChanged MVC refresh whole page - asp.net-mvc

I'm having a trouble while devolping my .net application.
I'm using the event OnTextChanged on a textbox to change the content in another Textbox, the first textbox has AutoPostBack="true", but when i write in it and click in another part, the page refreshes completely.
here is my ascx code:
<form id="Form1" runat="server">
Change text
<asp:TextBox id="txt1" runat="server" ontextchanged="ejemplo" autopostback="true"/>
<p><asp:Label id="lbl1" runat="server" /></p>
</form>
and the script in the same ascx page:
<script runat="server">
protected void ejemplo(object sender, EventArgs e)
{
lbl1.Text = "Changed";
}
</script>
I'm using MVC4,
Thanks for your answers.
EDIT:
here is a video of what is really happening:
http://remainedesign.com/video/asd.html

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 Textbox2 while entering a Value into the Textbox1 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" id="textbox1" name="Message" onkeyup="textCounter(this,'textbox2',208)"/>
<input disabled maxlength="3" size="3" value="208" id="textbox2" /></label>
<input type="submit" value="Send" />
<%}%>
Here
textCounter() function on keyup event in textbox1 will display value in textbox2,
submit button will submit form which call 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");
}
}
please note,above example is solely for MVC project
i hope this example may help you..

the first textbox has AutoPostBack="true", but when i write in it and
click in another part, the page refreshes completely
That is exactly what AutoPostBack is for. If you click on another part, that's when you lose focus on the textbox and it will trigger a postback. If you need more proof then read this from MSDN:
Gets or sets a value that indicates whether an automatic postback to
the server occurs when the TextBox control loses focus.

Related

Asp.net MVC button does not show

I place a button in a div tag, and when I run it, I only see the div container
<div style= "border-style:solid;border-width:1px; padding:5px; background-color:#ffffcc">
<asp:button ID = "refresh" runat ="server" OnClientClick="reloadPage()">
<script type="text/javascript">
function reloadPage(){
window.location.reload()
}
</script>
</asp:button>
</div>
the refresh button is nowhere can be found. Are there anything wrong with my code? I am new to MVC, please give me suggestions.
Why are you using asp controls in an MVC project -> use an HTML element.
Use a Form
<div>
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
<button type="submit">Submit</button>
}
</div>
Use a Button
<div>
<button onclick="DoSomeJavascript" >Submit</button>
</div>
MVC uses Controllers (Code Behind) and Views (Html) to create pages. To send data to or from a page you need to use View Models.
Maybe have a look at this handy guide: http://www.asp.net/mvc/overview/getting-started/introduction/getting-started
Your question states that you are new to MVC, yet you are trying to define a button from classic ASP.NET, which will not be processed by the Razor view engine used by MVC. Since you are just reloading the page you can do this with regular HTML buttons and Javascript. I'm not reloading the page here in this snippet, but that's irrelevant.
<div style="border-style:solid; border-width:1px; padding: 5px; background-color:#ffffcc">
<button id="refresh" onclick="reloadPage()">
Refresh Page
<script type="text/javascript">
function reloadPage() {
console.log("Reloaded")
//Reload page here
}
</script>
</button>
</div>
If you run this and click you should see the log message in your Javascript console.

Why Html.BeginForm in MVC4 is affected by the button click event,does it happen in MVC5?

My web page have a button and a form,I use #Html.BeginForm to produce the form and when I click the button,I will jump to the login page.To my surprise,when I click the button,the form post to my controller automatically.But when I use #using (Html.BeginForm,it seems OK.
My web page
<button onclick="logout()">logout</button>
#Html.BeginForm("ExportFile", "Student", new { id = "exportForm" }))
{
#Html.Hidden("year")
#Html.Hidden("fileName")
}
My new web page will work well
<button onclick="logout()">logout</button>
#using (Html.BeginForm("ExportFile", "Student", new { id = "exportForm" })))
{
#Html.Hidden("year")
#Html.Hidden("fileName")
}
I find the different HTML is System.Web.Mvc.Html.MvcForm):
<form id="exportForm" method="post" action="/Student/ExportFile">
System.Web.Mvc.Html.MvcForm) {
<input id="year" type="hidden" value="" name="year">
<input id="fileName" type="hidden" value="" name="fileName">
}
What is the difference between then?Someone teach me to add #{Html.EndForm();} when I using #Html.BeginForm,but it seems not work.May be it works in MVC3.
You can use these two methods only if you add the button type.
<button onclick="logout()" type="buttton">logout</button>
The using statement automatically adds the closing tag for the form's HTML. You should always use #using if you are using Html.BeginForm().

Repeater.Items only populates in Button click event when I DataBind in that event, but all textbox inputs are empty

I have a repeater that is databound to a SqlDataSource
<asp:Repeater runat="server" ID="Repeater" DataSourceID="SqlDataSource">
<ItemTemplate>
<asp:HiddenField runat="server" Value='<%# Eval("Code") %>' ID="Code" />
<asp:TextBox ID="NumberNeeded" runat="server" Text='<%# Eval("Needed") %>' /><br />
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" ID="submit" Text="submit" OnClick="submit_Click" />
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="rtvFiltered" SelectCommandType="StoredProcedure">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>
I want to iterate over the repeater and get the value in NumberNeeded in submit_Click
protected void submit_Click(object sender, EventArgs e)
{
this.Repeater.DataBind(); //comment this guy and this.Repeater.Items has no items
foreach (RepeaterItem item in this.Repeater.Items)
{
String code = ((HiddenField)item.FindControl("JournalCode")).Value;
// below fails because "NumberNeeded" control doesn't have the Text input by the user.
int numNeeded = Int32.Parse(((TextBox)item.FindControl("NumberNeeded")).Text);
// Doing other stuff with numNeeded
}
}
The repeater displays its items perfectly on the page, but when I click the submit button, this.Repeater.Items is empty (unless I call this.Repeater.DataBind() in that method).
I've tried explicitly data binding Repeater in Page_Load and Page_Init within and outside of a !Page.IsPostBack check, and everytime I either get no Items, or no Text value.
I have gotten an almost identical setup to work in the past, on a page without a master page. I've also noticed that this.Master.EnableViewState is false in the submit_Click method, no matter if I set it to true in Page_Init or Page_Load. this.EnableViewState is true.
As you state, you shouldn't need to call DataBind() in your code behind, so the problem may be with the data retrieval. Does your stored procedure take any parameters? Have you tried adding CancelSelectOnNullParameter="false" to your SqlDataSource?
It was the EnableViewState setting on the master page.
In the Page_Load method of the master page this.EnableViewState was getting set to false. I changed it to Page.EnableViewState and everything worked.
this.EnableViewState = Page.EnableViewState; // add to Master page Page_Load method
do'h

MVC 4 Ajax.beginform submit - causes full postback

MVC4 Internet project
I'm using Ajax.BeginForm to do a Postback with validation and it posts back the entire page rather than just the UpdateTargetID. I've looked at other posts on SO and haven't found the answer. I've built a new MVC4 Internet project just for testing (VS 2012 has been updated with 'ASP.NET and Web Tools 2012.2').
Here's my code
Controller
public ActionResult Index()
{
var vM = _db.Students.FirstOrDefault(); return View(vM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Student vM)
{
if (ModelState.IsValid)
{ //code if Model valid
return Json(new { url = Url.Action("About", "Controller") });
}
ModelState.AddModelError(string.Empty, "AJAX Post");
return PartialView("Index", vM);
}
View
#model AJAX_Test.Models.Student
#{ ViewBag.Title = "Student"; }
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript"> var onSuccess = function (result)
{
if (result.url) { window.location.href = result.url; }
}
// when server returns JSON object containing an url property redirect the browser </script>
<h1>#ViewBag.Title</h1>
<div id="IDXForm">
#using (Ajax.BeginForm("Index", new AjaxOptions() { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess", HttpMethod = "Post" }))
{
#Html.AntiForgeryToken() #Html.ValidationSummary(true)
<span>#Html.EditorFor(m => m.FirstName) #Model.EnrollmentDate.ToShortDateString()</span> <input type="submit" value="Submit" />
}
</div>
The initial view is:
After Submittal:
Source code for body after submittal:
<div id="body">
<section class="content-wrapper main-content clear-fix">
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript"> var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } }
// when server returns JSON object containing an url property redirect the browser </script>
<h1>Student</h1>
<div id="IDXForm">
<form action="/" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="onSuccess" data-ajax-update="#IDXForm" id="form0" method="post"><input name="__RequestVerificationToken" type="hidden" value="vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1" /><span><input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="Carson" /> 9/1/2005</span> <input type="submit" value="Submit" />
</form></div>
Can anyone see what is wrong with my code?
Thank you.
A couple of things that come to mind that might be causing this behavior:
In your question you have shown your bundle registrations but have you actually included them in your view or Layout? Make sure that in your view or layout you have first included jquery.js and then jquery.unobtrusive-ajax.js (in that order):
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
The jquery.unobtrusive-ajax.js script is not compatible with jquery 1.9 and later because it relies on the .live() which has been removed in jQuery 1.9. So if for some reason you have upgraded your jQuery version to 1.9 or later that won't work. You should downgrade.
In your onSuccess callback you are redirecting to an url if the controller action returns a JSON. Have you verified that this is not the case? Because when a redirect happens using the window.location.href it's pretty normal that you get a full page reload and not a partial update
In all cases use a javascript debugging tool to see what exactly is happening. If you are using Firefox, then you could use FireBug. If you are using Google Chrome, you could use the Chrome Developer Toolbar. Look at the console for potential javascript errors you might have. Look at the network tab to see whether all javascripts are successfully loaded and you don't have 404 errors. Learn how to debug your javascript code with a tool. You will be surprised how much information about potential issues you might have with your code those tools will provide you.
The contents of the UpdateTargetID must be in a partial view and that partial view needs to be called from the Controller Post Action. Darin answered me through e-mail (thank you Darin). You need to use a parital view. I've tried to update his answer twice and the moderators have not done it or provided an explanation why so I'm posting my own answer for others benefit.
_MyForm View:
#model AJAX_Test.Models.Student
#using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<span>
#Html.EditorFor(m => m.FirstName) #Model.EnrollmentDate.ToShortDateString()
</span>
<input type="submit" value="Submit" />
}
Main View :
<div id="IDXForm">
#Html.Partial("_MyForm")
</div>
Controller Post Action:
ModelState.AddModelError(string.Empty, "AJAX Post");
return PartialView("_MyForm", vM);
use:<script src="../Scripts/jquery.unobtrusive-ajax.js"></script>
This JS is what makes Ajax work.
Couple of other things to note.
jquery.unobtrusive-ajax.js now supports JQuery 1.9. I have installed jquery.unobtrusive-ajax.js version 3.0.0 and it is working with JQuery 1.9
2. Make sure all the div tages are closed properly, including the view which contains the Ajax.BeginForm and the main view. Also if you have #Html.Raw() in the main view or inside the view which contains Ajax.BeginForm be cautious about that too.
Posting here to save one day of head scratching.
make sure you have your bundles config include this
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
At a minimum, you need these two includes:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
And if that still does not help, check in web.config and make sure unobtrusive is enabled:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
And if that still has no effect, make sure unobtrusive js files are compatible with current jQuery version, whatever version of jQuery you are using, which can be found at a below URL:
http://www.nuget.org/packages?q=unobtrusive

dynamically filled div controls gets blank when page gets postback

I am working on asp.net, C# web application.
Working on my main page in application, where all the codes are synchronize and works well.
Now, I need to change some of the functionality using ajax JQuery Asyn. calls. In my case it works for me. everything is fine.
Now my page is having asp.net AjaX Timer Control which gets fire at every one minute. This is one of the functionality which is need to be there and not able to change using jQuery.
Now, when my timer event (Tick) fires at every one minute, my dynamically filled div ( html() of ajax jquery) gets blank when page gets postback.
i.e. consider my page having div with id = div1, and this gets filled with ajax jQuery call which returns me html of remote page, so the content of that is totally dynamic.
When page gets fired, that div is blank..
How can I keep my div's to be as it is when my page gets post back?
(think this is possible as Gmail works on the same thing, how they mantain?)
Please let me know if require more details if not clear.
Below is the image with ajax call.
now, when pages gets postback, it is something like below....
it is not possible for me to give complex code here, how ever i give a sample code here by.
<asp:ScriptManager ID="Scriptmanager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="5000" OnTick="Timer1_Tick" Enabled="true">
</asp:Timer>
<div>
<asp:Button Text="text" runat="server" OnClientClick="callfun();return false;" />
</div>
<asp:Button Text="text" runat="server" ID="btn" OnClick="btn_Click" />
<div id="div1">
</div>
<script>
});
function callfun() {
$("#div1").html("test me, test me");
}
</script>
code behind.....
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("postback");
}
protected void Timer1_Tick(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
}
Please use pageLoad(). It gets fired after each update panel refresh.
var cached_html;
$(document).ready(function() {
cached_html = "html returned from an ajax call"
$("#div1").html(cached_html);
});
function pageLoad() {
$("#div1").html(cached_html);
//if this doesn't work, you need to make ajax call each time the refresh happens
}
And forget gmail for now. They do not have a Sys is undefined :)

Resources