Submit data along with File Upload - asp.net-mvc-4

I am trying to post form data (such as textbox, checkbox etc) along with a File Upload . I am using MVC.
Any one give me a solutions?

There are so many ways to do it with MVC, with strong-typed as suggested above or this way also would work
[HttpPost]
public JsonResult CreateUpdate(FormCollection _formValues, YourModel _extraItem)
{
HttpPostedFileBase files = HttpContext.Request.Files;
//do whatever u wish with ure files here
}
hope it helps

Your Post Controller will look like this :
[HttpPost]
public ActionResult YourController(YourModel model1, HttpPostedFileBase file)
{
if (file != null)
{
//here file variable will have the file which you have uploaded
}
}
HttpPostedFileBase contains the file which you have posted from View.
and in your view BeginForm() should look like :
Html.BeginForm(action, controller, FormMethod.Post, new { enctype="multipart/form-data"})

i use XMLHttpRequest to resolve this solution. Thanks everyone so much :D

Related

Variable number of HttpPostedFileBase objects

Currently, I have this:
public ActionResult Add(FormCollection form, HttpPostedFileBase fr, HttpPostedFileBase en, HttpPostedFileBase es)
{
Upload(fr, "fr");
Upload(en, "en");
Upload(es, "es");
...
}
This works for what we're doing currently, but just learned of a new requirement where the system needs the ability to add other languages. This is the only part where I have an issue.
I tried:
public ActionResult Add(FormCollection form, HttpPostedFileBase[] fr)
{
foreach(var file in fr)
{
Upload(file, "I'mStuck");
}
...
}
as a test, but it will only have 1 element and it is the one where id/name = fr. Makes sense, but not particularly helpful for what I need.
I could do:
for (string file in Request.Files)
{
...
}
which would handle the upload component fine, but the issue is that unless I can force them to standardize against a whatever_langabbreviation.extension file format, which I can't, I'm not going to be able to know what the language abbreviation is.
How can I obtain the id/name fields for the input type=file objects within the controller?
I was actually incorrect. The string returned is actually the id or name (think name, but considering I typically pair id/name, it works).
For the controller that renders the view initially, I did:
List<Languages> langs = db.Languages.ToList();
viewmodel.Languages = langs;
return View(viewmodel);
In the view itself:
foreach(Language lang in Model.Languages)
{
// Label
<input type="file" id="#lang.Abbreviation" name="#lang.Abbreviation" />
}
And in the post event:
foreach(string file in Request.Files)
{
HttpPostedFileBase fb = Request.Files[file];
Upload(fb, file);
}
And it handles as it is supposed to (Upload being a function that just adds a new item to another table.

The view or its master was not found or no view engine supports the searched locations

Error like:The view 'LoginRegister' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/MyAccount/LoginRegister.aspx
~/Views/MyAccount/LoginRegister.ascx
~/Views/Shared/LoginRegister.aspx
~/Views/Shared/LoginRegister.ascx
~/Views/MyAccount/LoginRegister.cshtml
~/Views/MyAccount/LoginRegister.vbhtml
~/Views/Shared/LoginRegister.cshtml
~/Views/Shared/LoginRegister.vbhtml
Actually my page view page is ~/Views/home/LoginRegister.cshtml so what i do
and my RouteConfig is
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "MyAccount", action = "LoginRegister", id = UrlParameter.Optional }
);
}
}
Be careful if your model type is String because the second parameter of View(string, string) is masterName, not model. You may need to call the overload with object(model) as the second parameter:
Not correct :
protected ActionResult ShowMessageResult(string msg)
{
return View("Message",msg);
}
Correct :
protected ActionResult ShowMessageResult(string msg)
{
return View("Message",(object)msg);
}
OR (provided by bradlis7):
protected ActionResult ShowMessageResult(string msg)
{
return View("Message",model:msg);
}
Problem:
Your View cannot be found in default locations.
Explanation:
Views should be in the same folder named as the Controller or in the Shared folder.
Solution:
Either move your View to the MyAccount folder or create a HomeController.
Alternatives:
If you don't want to move your View or create a new Controller you can check at this link.
In Microsoft ASP.net MVC, the routing engine, which is used to parse incoming and outgoing URL Combinations, is designed with the idea of Convention over Configuration. What this means is that if you follow the Convention (rules) that the routing engine uses, you don't have to change the Configuration.
The routing engine for ASP.net MVC does not serve web pages (.cshtml). It provides a way for a URL to be handled by a Class in your code, which can render text/html to the output stream, or parse and serve the .cshtml files in a consistent manner using Convention.
The Convention which is used for routing is to match a Controller to a Class with a name similar to ControllerNameController i.e. controller="MyAccount" means find class named MyAccountController. Next comes the action, which is mapped to a function within the Controller Class, which usually returns an ActionResult. i.e. action="LoginRegister" will look for a function public ActionResult LoginRegister(){} in the controller's class. This function may return a View() which would be by Convention named LoginRegister.cshtml and would be stored in the /Views/MyAccount/ folder.
To summarize, you would have the following code:
/Controllers/MyAccountController.cs:
public class MyAccountController : Controller
{
public ActionResult LoginRegister()
{
return View();
}
}
/Views/MyAccount/LoginRegister.cshtml: Your view file.
In your LoginRegister action when returning the view, do below, i know this can be done in mvc 5, im not sure if in mvc 4 also.
public ActionResult Index()
{
return View("~/Views/home/LoginRegister.cshtml");
}
Check the build action of your view (.cshtml file) It should be set to content. In some cases, I have seen that the build action was set to None (by mistake) and this particular view was not deploy on the target machine even though you see that view present in visual studio project file under valid folder
This could be a permissions issue.
I had the same issue recently. As a test, I created a simple hello.html page. When I tried loading it, I got an error message regarding permissions. Once I fixed the permissions issue in the root web folder, both the html page and the MVC rendering issues were resolved.
Check whether the View (.ASPX File) that you have created is having the same name as mentioned in the Controller. For e.g:
public ActionResult GetView()
{
return View("MyView");
}
In this case, the aspx file should be having the name MyView.aspx instead of GetView.aspx
I got this error because I renamed my View (and POST action).
Finally I found that I forgot to rename BOTH GET and POST actions to new name.
Solution : Rename both GET and POST actions to match the View name.
If the problem happens intermittently in production, it could be due to an action method getting interrupted. For example, during a POST operation involving a large file upload, the user closes the browser window before the upload completes. In this case, the action method may throw a null reference exception resulting from a null model or view object. A solution would be to wrap the method body in a try/catch and return null. Like this:
[HttpPost]
public ActionResult Post(...)
{
try
{
...
}
catch (NullReferenceException ex) // could happen if POST is interrupted
{
// perhaps log a warning here
return null;
}
return View(model);
}
I had this same issue.
I had copied a view "Movie" and renamed it "Customer" accordingly.
I also did the same with the models and the controllers.
The resolution was this...I rename the Customer View to Customer1 and
just created a new view and called it Customer....I then just copied
the Customer1 code into Customer.
This worked.
I would love to know the real cause of the problem.
UPDATE
Just for grins....I went back and replicated all the renaming scenario again...and did not get any errors.
I came across this error due to the improper closing of the statement,
#using (Html.BeginForm("DeleteSelected", "Employee", FormMethod.Post))
{
} //This curly bracket needed to be closed at the end.
In Index.cshtml view file.I didn't close the statement at the end of the program. instead, I ended up closing improperly and ran into this error.
I was sure there isn't a need of checking Controller ActionMethod code because I have returned the Controller method properly to the View. So It has to be the view that's not responding and met with similar Error.
If you've checked all the things from the above answers (which are common mistakes) and you're sure that your view is at the location in the exceptions, then you may need to restart Visual Studio.
:(
In my case, I needed to use RedirectToAction to solve the problem.
[HttpGet]
[ControleDeAcessoAuthorize("Report/ExportToPDF")]
public ActionResult ExportToPDF(int id, string month, string output)
{
try
{
// Validate
if (output != "PDF")
{
throw new Exception("Invalid output.");
}
else
{
...// code to generate report in PDF format
}
}
catch (Exception ex)
{
return RedirectToAction("Error");
}
}
[ControleDeAcessoAuthorize("Report/Error")]
public ActionResult Error()
{
return View();
}
I ran into this a while ago and it drove me crazy because it turned out to be simple. So within my View I was using a grid control that obtained data for the grid via an http request. Once the middle tier completed my request and returned the dataset, I received the same error. Turns out my return statement was 'return View(dataset);' instead of 'return Json(dataset);
I couldn't find any solution to this problem, until I found out the files didn't exist!
This took me a long time to figure out, because the Solution Explorer shows the files!
But when I click on Index.cshtml I get this error:
So that was the reason for this error to show. I hope this answer helps somebody.

HTTP GET to return custom model with data from external database with Umbraco MVC Surface Controller

I am currently working on an Umbraco MVC 4 project version 6.0.5. The project currently uses Vega.USiteBuilder to build the appropriate document types in the backoffice based on strongly typed classes with mapping attributes. Consequently, all my razor files inherit from UmbracoTemplatePageBase
I am coming across a road block trying to invoke a HTTP GET from a razor file. For example a search form with multiple fields to submit to a controller action method, using a SurfaceController using Html.BeginUmbracoForm.
My Html.BeginUmbracoForm looks like this
#using (Html.BeginUmbracoForm("FindTyres", "TyreSearch"))
{
// Couple of filter fields
}
I basically have a scenario where I will like to retrieve some records from an external database outside of Umbraco (external to Umbraco Database) and return the results in a custom view model back to my Umbraco front end view. Once my controller and action method is setup to inherit from SurfaceController and thereafter compiling it and submitting the search, I get a 404 resource cannot be found where the requested url specified: /umbraco.RenderMVC.
Here is my code snippet:
public ActionResult FindTyres(string maker, string years, string models, string vehicles)
{
var tyreBdl = new Wheels.BDL.TyreBDL();
List<Tyre> tyres = tyreBdl.GetAllTyres();
tyres = tyres.Where(t => string.Equals(t.Maker, maker, StringComparison.OrdinalIgnoreCase)
&& string.Equals(t.Year, years, StringComparison.OrdinalIgnoreCase)
&& string.Equals(t.Model, models, StringComparison.OrdinalIgnoreCase)
&& string.Equals(t.Version, vehicles, StringComparison.OrdinalIgnoreCase)).ToList();
var tyreSearchViewModel = new TyreSearchViewModel
{
Tyres = tyres
};
ViewBag.TyreSearchViewModel = tyreSearchViewModel;
return CurrentUmbracoPage();
}
I then resort to using standard MVC, Html.BeginForm (the only difference). Repeating the steps above and submitting the search, I get the following YSOD error.
Can only use UmbracoPageResult in the context of an Http POST when
using a SurfaceController form
Below is a snippet of the HTML BeginForm
#using (Html.BeginForm("FindTyres", "TyreSearch"))
{
// Couple of filter fields
}
I feel like I am fighting the Umbraco routes to get my controller to return a custom model back to the razor file. I have googled alot trying to figure out how to do a basic search to return a custom model back to my Umbraco front end view till the extent that I tried to create a custom route but that too did not work for me.
Does my controller need to inherit from a special umbraco controller class to return the custom model back? I will basically like to invoke a HTTP GET request (which is a must) so that my criteria search fields are reflected properly in the query strings of the url. For example upon hitting the search button, I must see the example url in my address browser bar
http://[domainname]/selecttyres.aspx/TyresSearch/FindTyresMake=ASIA&Years=1994&Models=ROCSTA&Vehicles=261
Therefore, I cannot use Surface Controller as that will operate in the context of a HTTP Post.
Are there good resource materials that I can read up more on umbraco controllers, routes and pipeline.
I hope this scenario makes sense to you. If you have any questions, please let me know. I will need to understand this concept to continue on from here with my project and I do have a deadline.
There are a lot of questions about this and the best place to look for an authoritative approach is the Umbraco MVC documentation.
However, yes you will find, if you use Html.BeginUmbracoForm(...) you will be forced into a HttpPost action. With this kind of functionality (a search form), I usually build the form manually with a GET method and have it submit a querystring to a specific node URL.
<form action="#Model.Content.Url"> ... </form>
On that page I include an #Html.Action("SearchResults", "TyresSearch") which itself has a model that maps to the keys in the querystring:
[ChildAction]
public ActionResult(TyreSearchModel model){
// Find results
TyreSearchResultModel results = new Wheels.BDL.TyreBDL().GetAllTyres();
// Filter results based on submitted model
...
// Return results
return results;
}
The results view just need to have a model of TyreSearchResultModel (or whatever you choose).
This approach bypasses the need for Umbraco's Controller implementation and very straightforward.
I have managed to find my solution through route hijacking which enabled me to return a custom view model back to my view and work with HTTP GET. It worked well for me.
Digby, your solution looks plausible but I have not attempted at it. If I do have a widget sitting on my page, I will definitely attempt to use your approach.
Here are the details. I basically override the Umbraco default MVC routing by creating a controller that derived from RenderMvcController. In a nutshell, you implement route hijacking by implementing a controller that derives from RenderMvcController and renaming your controllername after your given documenttype name. Recommend the read right out of the Umbraco reference (http://our.umbraco.org/documentation/Reference/Mvc/custom-controllers) This is also a great article (http://www.ben-morris.com/using-umbraco-6-to-create-an-asp-net-mvc-4-web-applicatio)
Here is my snippet of my code:
public class ProductTyreSelectorController : Umbraco.Web.Mvc.RenderMvcController
{
public override ActionResult Index(RenderModel model)
{
var productTyreSelectorViewModel = new ProductTyreSelectorViewModel(model);
var maker = Request.QueryString["Make"];
var years = Request.QueryString["Years"];
var models = Request.QueryString["Models"];
var autoIdStr = Request.QueryString["Vehicles"];
var width = Request.QueryString["Widths"];
var aspectRatio = Request.QueryString["AspectRatio"];
var rims = Request.QueryString["Rims"];
var tyrePlusBdl = new TPWheelBDL.TyrePlusBDL();
List<Tyre> tyres = tyrePlusBdl.GetAllTyres();
if (Request.QueryString.Count == 0)
{
return CurrentTemplate(productTyreSelectorViewModel);
}
if (!string.IsNullOrEmpty(maker) && !string.IsNullOrEmpty(years) && !string.IsNullOrEmpty(models) &&
!string.IsNullOrEmpty(autoIdStr))
{
int autoId;
int.TryParse(autoIdStr, out autoId);
tyres = tyres.Where(t => string.Equals(t.Maker, maker, StringComparison.OrdinalIgnoreCase) &&
string.Equals(t.Year, years, StringComparison.OrdinalIgnoreCase) &&
string.Equals(t.Model, models, StringComparison.OrdinalIgnoreCase) &&
t.AutoID == autoId)
.ToList();
productTyreSelectorViewModel.Tyres = tyres;
}
else if (!string.IsNullOrEmpty(width) && !string.IsNullOrEmpty(aspectRatio) && !string.IsNullOrEmpty(rims))
{
tyres = tyres.Where(t => string.Equals(t.Aspect, aspectRatio, StringComparison.OrdinalIgnoreCase) &&
string.Equals(t.Rim, rims, StringComparison.OrdinalIgnoreCase)).ToList();
productTyreSelectorViewModel.Tyres = tyres;
}
var template = ControllerContext.RouteData.Values["action"].ToString();
//return an empty content result if the template doesn't physically
//exist on the file system
if (!EnsurePhsyicalViewExists(template))
{
return Content("Could not find physical view template.");
}
return CurrentTemplate(productTyreSelectorViewModel);
}
}
Note my ProductTyreSelectorViewModel must inherit from RenderModel for this to work and my document type is called ProductTyreSelector. This way when my model is returned with the action result CurrentTemplate, the Umbraco context of the page is retained and my page is rendered appropriately again. This way, all my query strings will show all my search/filter fields which is what I want.
Here is my snippet of the ProductTyreSelectorViewModel class:
public class ProductTyreSelectorViewModel : RenderModel
{
public ProductTyreSelectorViewModel(RenderModel model)
: base(model.Content, model.CurrentCulture)
{
Tyres = new List<Tyre>();
}
public ProductTyreSelectorViewModel(IPublishedContent content, CultureInfo culture)
: base(content, culture)
{
}
public ProductTyreSelectorViewModel(IPublishedContent content)
: base(content)
{
}
public IList<Tyre> Tyres { get; set; }
}
This approach will work well perhaps with one to two HTTP GET forms on a given page. If there are multiple forms within in a page, then a good solution will may be to use ChildAction approach. Something I will experiment with further.
Hope this helps!

MVC 4 Partial with separate Controller and View

I've developed ASP.NET Forms for some time and now am trying to learn MVC but it's not making total sense how to get it to do what I want. Perhaps I need to think about things differently. Here is what I'm trying to do with a made up example:
Goal - Use a partial file, which can be placed anywhere on the site which will accept a parameter. That parameter will be used to go to the database and pass back the resulting model to the view. The view will then display one or more of the models properties.
This isn't my code, but shows what I'm trying to do.
File: Controllers/UserController.cs
[ChildActionOnly]
public ActionResult DisplayUserName(string userId)
{
MyDataContext db = new MyDataContext()
var user = (from u in db.Users where u.UserId = userId select u).FirstOrDefault();
return PartialView(user);
}
File: Views/Shared/_DisplayUserName.cs
#model DataLibrary.Models.User
<h2>Your username is: #Model.UserName</h2>
File: Views/About/Index.cshtml
#{
ViewBag.Title = "About";
}
<h2>About</h2>
{Insert Statement Here}
I know at this point I need to render a partial called DisplayUserName, but how does it know which view to use and how do I pass my userId to the partial?
It's what I expect is a very basic question, but I'm yet to find a tutorial which covers this.
Thanks in advance for your help.
You should call Html.Action or Html.RenderAction like:
#Html.Action("DisplayUserName", "User", new {userId = "pass_user_id_from_somewhere"});
Your action should be like:
[ChildActionOnly]
public ActionResult DisplayUserName(string userId)
{
MyDataContext db = new MyDataContext()
var user = (from u in db.Users where u.UserId = userId select u).FirstOrDefault();
return PartialView("_DisplayUserName", user);
}
This should do the trick.
I always make sure to close the MyDataContext... Maybe enclose everything in a using statement... If you notice when VS does it for you they create the entity as a private variable in the Controller Class (outside of the controllers) and then close it with the dispose method... Either way I believe you need to make sure those resources are released to keep things running smooth. I know it's not in the question but I saw that it looked vulnerable.

Linq to Sql in mvc 4

I'm having some problems editing an object in the mvc4 framework using linq to sql.
The "tbBoeking" object has been generated by Visual Studio 2010 and resides in a .dbml file. It has just been generated and no alterations have been made to it or the database.
Code in BoekingController.cs:
//This class has been generated and resides in a .dbml file
private DataClassesDataContext db = new DataClassesDataContext();
//Display edit form
public ActionResult Edit(int id = 0)
{
tbBoeking boeking = db.tbBoekings.Single(p => p.boeknummer == id);
if (boeking == null)
{
return HttpNotFound();
}
return View(boeking);
}
//Process changes made in form
[HttpPost]
public ActionResult Edit(tbBoeking boeking)
{
if (ModelState.IsValid)
{
db.tbBoekings.Attach(boeking, true);
db.SubmitChanges();
return RedirectToAction("Index");
}
return View(boeking);
}
Displaying the edit form works fine but when I press submit and the second Edit() is called things go wrong:
On db.submitchanges() I get an error which simply states:
"Row not found or changed".
I have read a few other posts about this error but they were not helpful for me. I think I'm making some basic mistake with Linq-to-sql or concurrency. Am I using Attach() in the wrong place or is it something else?
Thanks in advance,
Blight
Is all of the required information filled in? Also, do you have some sort of timestamp that might need updated. I have heard of the code ignoring the asUpdated flag if a versioning system is in place. That error can be very generic, so checking some other things can help
If the above suggestions do not help, then I would run a SQL profiler trace to see the SQL that is being fed to the server.