views:

70

answers:

2

I am doing what would take me less that 2hours to do in old ASP.Net Web Forms but has left me stumped in how to implement in ASP.Net MVC.

Problem: I am trying to put together a really basic admin site about musicians. a musician has a associated picture of them, then some details like name, age, home town alongside the profile pic. really basic...

when a admin user creates a muscian, the create view has a file upload, and onchange of the file upload, a preview image should appear. the create page also has the form fields for the other inputs.

In the details view, the musician's profile picture should appear alongside the details.

when in edit mode, again, the exsting image should appear, and if the user chooses to change the picture, the picture again will change there on the spot, without reloading the page.

This seems increadibly easy, but i am really struggling to see how the ASP.Net MVC architecture makes this possible without a great deal of work.

Thanks in advance.

A: 

What part exactly are you having problems with? To upload a file you start with a form that posts a file and extra properties like this.

<form action="yourcontroller/savefile" method="post" enctype="mulitipart/form-data">
     <input type="file" name="file" />
     <input type="text" name="other" />
</form>

Then you will need a controller action to handle the post. The file can be bound to a HttpPostedFileBase object which has a method to save it. Other form inputs can also be bound. Finally to display the image you just need to pass the image path to the a view to render it.

public ActionResult SaveFileAction(string other, HttpPostedFileBase file)
{
    file.SaveAs("/path/to/save/");       // Note Server.MapPath() converts urls to     
                                         // a physical path which might help.

    ViewData["path"] = "/url/to/image";  // Add the URL to the view date so we can 
                                         // use it in the view

    return View();
}

Finally in the view view we can render the uploaded image.

<img src="<%= imageUrl %>" />

Clearly you will have more to consider for your application, but hopefully this helps show that uploading and then displaying images in ASP.NET MVC is not too much work.

tarn
A: 

This doesn't really have much to do with MVC architecture. I think you might need to research uploading images with AJAX and the limitations there are. There are numerous workarounds using iframes to achieve the result you are trying to get.

Simon Hazelton