locked
MVC Onclick RRS feed

  • Question

  • User1258073786 posted

    Hi, sorry if i asking stupid question, but i just wish to know that how MVC actually handle button onclick or dropdown onselect event??

    because i had been trying for few days still cant get the solution. i just wan my image button to make another text box visible once the image button is clicked. can anyone tell me how to do this?? i am just starting to use asp  for my final year project and my first start is in MVC..my frens keep telling me the way to do it in traditional asp approach, but i wonder is it really harder to do this with MVC??

    Really need an solution for this...appreciate your help...

    Thursday, March 17, 2011 3:36 AM

Answers

All replies

  • User-821857111 posted

    You need to use JavaScript. Read this article, but scroll half way down to Where's My AutoPostback: http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 17, 2011 4:01 AM
  • User654067467 posted

    Mikes article is a very fine example on how to work with dropdownlists and how to do the "onselectionchanged" stuff in MVC :). More specificly for your problem however I'd say you need to get some hands on with jQuery. What you want to do is make a textbox visible after a click on an imagebutton you could solve this without any postback to the server at all:

    <html>
    <head>
    <title>My cool webpage!</title>
    <script type="text/javascript" language="javascript" src="/Scripts/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">
    function makevisible() {
        $('#MyHiddenTextBox').show();
    }
    </script>
    </head>
    <body>
    Your textbox:<br />
    <input type="text" id="MyHiddenTextBox" style="display:none;" /><br/>
    
    Your imagebutton:<br/>
    <input type="image" src="/Images/coolimage.png" onclick="makevisible();" />
    </body>
    </html>
    If you need more specific example just let me know :)

    Thursday, March 17, 2011 6:33 AM
  • User1258073786 posted

    I am so glad to receive all helps here. but sorry to ask that, where should i put the script tag? in the View?

    and for the dropdown, after gone through the article, i still not really clear about the method we can use to call and handle the postback event once a specific item in the dropdown is seleted...

    really thanks a lot..

    Thursday, March 17, 2011 6:51 AM
  • User654067467 posted

    If you're referring to the small piece of javascript I wrote, then yes all I did was write a tiny webpage (aka View) that has an image button and have a textbox appear through use of jQuery. In my projects the jQuery is included in the master page of my site so I don't need to include that reference in my views.

    Regarding the dropdown: I'm unsure if you are familiar about how forms work in pure HTML and HTTP but when choosing MVC you take a step down deeper and closer to that. The article shows you 2 ways of binding the 'onchange' event of the dropdown to submit the form that surrounds your dropdown. Personally I prefer the 2nd one by making use of jQuery to bind the actions.

    So you create a form setting its method and target and then add your dropdown in there filling it with options or making use of information in your model along with the HtmlHelper. I will take Mike's example for a moment and elaborate:

    <script type="text/javascript">
      $(function() {
        $("#CategoryID").change(function() {
          $('#TheForm').submit();
        });
      });
    </script>
    
    <%using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "TheForm" })){%>
      <%=Html.DropDownList("CategoryID", (SelectList) ViewData["Categories"], "--Select One--") %>
    <%}%> 
    
    

    (Take note above example is taken from Mike's article at http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists , credit where credit is due :) )

    This is also my personal favorite of how to create this type of action. First let me skip teh 'script' part a moment and elaborate on teh creation of the form itself. There's 4 important parameters there:

    "Index", "Home" => this is the controller and the action where posting back this form will end up. In Mike's example he creates a form that will post back to the 'Index' method of his 'Home' controller. This method will accept some form of the data you're sending to it. I see in the example this receiving end is kind of missing in the codeexamples but it'd look something like:

    public ActionResult Index(int categoryId)

    Ofcourse this isn't optimal, you'd normally post back your form to something like a CategoryController and have it hit the Index action there which could render an overview of products in your category.

    Then there's the formmethod which is set to 'POST'. This is important in cases like when you catch the postback in the same controller and method. You cannot make overloads with as only exception when you annotate these with methods of HTTP they accept. You could have these in your homecontroller for this example:

    [HttpGet]
    public ActionResult Index() //Returns the example form

    [HttpPost]
    public ActionResult Index(int categoryId) //Returns some form of reply to your selection

    And last but not least: the ID that the form will get is manually defined. This is to make it so that you can easily select it with jQuery.

    Then you see how the dropdown is created based on a list of items in the ViewData. This is an easy way of creating a datadriven dropdown, if the content is more static you can also type the HTML yourself ofcourse. Now to bind the 'onchange' there's again some jQuery involved. It binds the change event of the dropdown on an efficient and simple manner without you needing to make changes to how your dropdown is generated... this is important to note mainly because when you in the future want to start making things asynchronous with AJAX you can easily do so without having to touch anything but the little piece of javascript at the top of your view.

    In the example the function bound to the onchange submits the surrounding form causing your Index method on your Home controller to be called. If you used the receiving method I wrote in example above the selected category id will be inside the categoryId parameter that the method receives. If you haven't done that you can also find the posted id in the HttpContext.Request information.

    I'm sorry if this all seems a bit overwhelming and I tried to keep things to a minimum but I tend to get carried away by the extensiveness of possibilities that you have when writing applications in MVC. If you have a direct question for an example tailored to what you're doing don't hesitate to ask. And all others feel free to correct me if I forgot or overlooked something. :)

    Thursday, March 17, 2011 9:33 AM
  • User1258073786 posted

    Hi, i think i need to show some of my code here:

    I am following ur example and put it in my View (Add.ascx):

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<myFYP.Models.Food>>" %>
    
    <script type="text/javascript" language="javascript" src="/Scripts/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">
        function makevisible() {
            $('#MyHiddenTextBox').show();
        }
    </script>

    ...

    and my image button is here:

    <td>
                    <%: Html.ActionLink("Add", "Add", new { id=item.FoodID }) %>
                    <asp:ImageButton ID="ImageButton1" runat="server" Height="30px" ImageUrl="~/Content/images/add.png"
                        Width="30px" onclick="makevisible"  />|
    </td>

    textbox here:

     <td>
                    <%: item.FoodAmount %><input type="text" id="MyHiddenTextBox" style="display:none;" />
                </td>
    but when i try to run it, i get a compilation error:
    'ASP.views_shared_add_ascx'
    does not contain a definition for 'makevisible' and no extension method
    'makevisible' accepting a first argument of type
    'ASP.views_shared_add_ascx' could be found (are you missing a using
    directive or an assembly reference?)

    any idea why this happen??

    thanks so much...

    Thursday, March 17, 2011 4:52 PM
  • User1258073786 posted

    Hi, i got another problem here, once i change by image button from asp: Imagebutton to the <input> style u provided in example, it works and my textbox show once i click the image. However, may I knw why is it happening? and my problem is, the text box do not "stay", it just show out then hidden again..so i cannot put any value in it..

     

     

    Thursday, March 17, 2011 5:12 PM
  • User197322208 posted

    do not use WebForm controls in MVC projects.

    Please see also MVC MusicStore /NerdDinner tutorials.

    Thursday, March 17, 2011 6:10 PM
  • User1258073786 posted

    hihi, sorry to ask that, hw m i going to do this using pure MVC?? thanks a lot...

    Friday, March 18, 2011 12:42 AM
  • User197322208 posted

    hw m i going to do this using pure MVC??

    read again the answers in this thread. Basically, it is a javascript problem.

     

    Friday, March 18, 2011 1:20 AM
  • User654067467 posted

    Aye as Ignat has said do not use webforms controls in the middle of an mvc view.

    Also verify that you have indeed jQuery in your project as my "/Scripts/jquery.min.js" src was an example. I tested the little HTML I wrote in the most simple form (plain html file) with just a reference to jQuery and it worked as expected and the textbox would remain visible.

    If you don't have jQuery you can get it at http://docs.jquery.com/Downloading_jQuery

    You can get familiar with jQuery reading their documentation at http://docs.jquery.com/Main_Page

    Furthermore I'd advise you to follow the MVC tutorials at http://www.asp.net/mvc/tutorials

    For general knowledge and feeling with HTML and javascript (which you need for beign succesful with MVC) I also advise having a look on http://www.w3schools.com/

    Please do ask any questions if you have doubts regarding any of these.

    Friday, March 18, 2011 7:37 AM
  • User1258073786 posted

    hi, in fact beside jquery, i ald gone through the mvc tutorial and understand abt html. just that i nid to develop some part of my sys in a very very short time, i could not help to urge for solution. i had tried a fair amount of ways using a lot of time, but still cant get the picture clear. especially on html helper. i cant reli get one info which describe clearly about it.

    Friday, March 18, 2011 8:12 AM
  • User654067467 posted

    I understand that often you need to develop things faster then you're able to. To stay on topic: Did you verify that you have indeed the correct reference to jQuery?

    I understand that you changed

    <asp:ImageButton ID="ImageButton1" runat="server" Height="30px" ImageUrl="~/Content/images/add.png"
                       
    Width="30px" onclick="makevisible"  />

    into

    <input type="image" src="/Content/images/add.png" onclick="makevisible();" style="width:30px;height:30px;" />

    so if .show() isn't working as expected (displaying the textbox and leaving it there) I believe the jQuery reference may be wrong. You can test this easily by replacing "/Scripts/jquery.min.js" into "http://code.jquery.com/jquery-1.5.1.min.js".

    If I can provide you with a specific example for your situation I'm affraid I'll need a bit more context tough I firmly believe that there's just very small details that have to be fixed to make it work for you.

    Friday, March 18, 2011 8:49 AM
  • User1258073786 posted

    hi, may i knw what u mean by the "correct" reference to jquery?? anyway, after i change the src to the url u provided, the text box stll appear a while and disappear after loading.

    In fact i have a table, showing details of a stock. i got image button at each row, so tat user click the image button at the respective row, the quantity column should changed into a text field which let user to enter new quantity and save.

    currently not only the textbox will disappear, i also no idea how to make it actually "mask" the initial quantity display in text field (means once the textbox appear, it should cover the whole column). also, i realise that even i click the image button at column 2, only at column1 will display the text box...

     

    Friday, March 18, 2011 9:14 AM
  • User2141691880 posted

    u can see that i fill drop down on selection of other dropdown

    http://cid-ed5169ff8d4330c7.office.live.com/self.aspx/new/TestDropdown.rar


     

    
    Wednesday, April 20, 2011 2:27 AM