1

i am doing my project in asp.net MVC4 using c#

I am trying to select a photo and save that image in a folder,

for that i have an html Begin form

 @using (Html.BeginForm("ImageReplace", "Member", new { imgid = @Model.Id }, FormMethod.Post,new { enctype = "multipart/form-data" }))
  { 
     <input type="text" name="fake_section" class="fake_section"><button class="fake_section">Choose Photo</button>
     <input type="file" style="display:none;" name="file" id="file" value="Choose Photo" accept="image/png,image/jpeg" /> 
     <input type="submit" name="submit" value="Submit" />
   }

And i have a controller also

  public ActionResult ImageReplace(HttpPostedFileBase file,int imgid)
    {
        ......
    }

For styling and validating the form (only select the gif and jpeg files) i use the following jquery

 $('.fake_section').click(function (e) {
    e.preventDefault();

    $('#file').trigger('click');
});

$('#file').change(function (e) {
    var filename = $(this).val();
    var ext = filename.split('.').pop().toLowerCase();

    if ($.inArray(ext, ['gif', 'jpg', 'jpeg']) == -1) {
        alert('not valid!');
    }
    else {
        $('input[name="fake_section"]').val(filename);
    }
});

enter image description here

My problem is that when click to choose the photo it is directly go to Controller Action without selecting photo

5
  • 1
    Does changing the button to <input type="button" class="fake_section" value="Choose Photo"/> help? Commented Jan 17, 2014 at 6:21
  • Now it is not go to Controller .. but not selecting the image Commented Jan 17, 2014 at 6:23
  • By not selecting the image do you mean file chooser dialog is not opening? Commented Jan 17, 2014 at 6:25
  • Do you have proper version of jquery included? You might also try $('#file').click(); Commented Jan 17, 2014 at 6:28
  • ya i solve that problem .. thank you for helping me.. Commented Jan 17, 2014 at 6:30

1 Answer 1

3

I think that button type is missig. Look at this jsFiddle: http://jsfiddle.net/CJf9f/

<button class="fake_section" type="button">Choose Photo</button>
Sign up to request clarification or add additional context in comments.

1 Comment

This just helped me with my issue: multiple buttons within form, all were submitting form instead of triggering expected actions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.