Search code examples
asp.net-mvcupdatepanel

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?


Solution

  • 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..