So I have a project in which i want to upload video to dailymotion using api
So i want to Upload video directly to dailymotion server without uploading it to my local server
My Action
[HttpPost]
public async Task<ActionResult> Add(Video Videos)
{
var fileToUpload = #"E:\Courses\[FreeCourseLab.com] Udemy - C# Intermediate Classes, Interfaces and OOP\5. Polymorphism Third Pillar of OOP\3. Sealed Classes and Members.mp4";
return RedirectToAction("AddVideo", "Admin");
}
my View
#using (Html.BeginForm("Add", "Admin", FormMethod.Post, new { #class = "px-lg-4", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="input-group input-group--focus mb-lg-4" style="width: 100%">
<div class="input-group-prepend"></div>
#Html.TextBoxFor(m => m.Videos.File, new {#type="file" })
</div>
<input type="submit" class="d-flex justify-content-center btn btn-block btn-primary" value="Create" />
}
Related
I have a table view with list of roles and an action link to create new roles. Below is my roles.cshtml page
#model List<ExpenCare.Models.CompanyRole>
<div class="row">
#Html.Partial("_RightSidePane")
<div class="col-10 col-sm-8 col-xs-8 col-md-10">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-Roles-Content" role="tabpanel" aria-labelledby="list-Roles"></div>
#using (#Html.BeginForm("UpdateRoles", "Admin", FormMethod.Post))
{
<table class="table">
<tr>
<th>
Name
</th>
<th>
Enable
</th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.HiddenFor(m => m[i].Id)
#Html.HiddenFor(m => m[i].Name)
#Html.DisplayFor(m => m[i].Name)
</td>
<td>
#Html.EditorFor(m => m[i].Enabled, new { #checked = "checked" })
</td>
</tr>
}
</table>
<p><input type="submit" value="Save Changes" /></p>
<p style="color:green; font-size:12px;">#ViewBag.Message</p>
<p>
#Html.ActionLink("Create new Roles", "ViewCreateRoles", "Admin", null, new { id = "CreateRoles", #class = "appao-btn" })
</p>
}
</div>
</div>
</div>
"Create new roles" button calls to ViewCreateRoles method in admin controller, which stated below.
public ActionResult ViewCreateRoles()
{
return View("Roles/CreateRoles");
}
In CreateRoles.cshtml page user can create a role and submit. when submitting it redirects to action CreateRoles in the same admin controller.
#model ExpenCare.Models.CompanyRole
#{
ViewBag.Title = "CreateRoles";
}
<div class="row">
#Html.Partial("_RightSidePane")
<div class="col-10 col-sm-8 col-xs-8 col-md-10">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="list-Profile-Content" role="tabpanel" aria-labelledby="list-Profile">
#using (Html.BeginForm("CreateRoles", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enabled, "Enable", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Enabled)
#Html.ValidationMessageFor(model => model.Enabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
</div>
</div>
</div>
Below is the CreateRoles methodin admin controller.
public ActionResult CreateRoles(CompanyRole role)
{
List<CompanyRole> roles;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:1888/api/");
var responseTask = client.PostAsJsonAsync("CompanyRoles", role);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<List<CompanyRole>>();
readTask.Wait();
roles = readTask.Result;
return View("Roles/Roles", model: roles);
}
else
{
ViewBag.Message = "not updated.";
return View("Roles/CreateRoles");
}
}
After creating a role on success user is redirecting to roles.cshtml mentioned above which shows all the roles. My problem is that my process of adding a role (go to roles page-> create new role-> redirect to roles page) is working fine. But just after redirecting to the roles page I get "An exception of type 'System.Web.Http.HttpResponseException' occurred in ExpenCare.dll but was not handled in user code" error in my web api which is getting called in CreateRoles. when I debug the process I see that after going to "Dispose" method of admin contoller "CreateRoles" method is getting called again and null "CompanyRole role" data is passed to the web API. I dunno how it is getting called again. I checked in google and tried removing all "#" from href and src of my view and layout pages, but it is still not working. I can't find why the same method is getting called twice without the button click.
I have two models where I have used Tuple to implement it like this
#using WorkFlowManagement.Entity
#model Tuple<FormModel, ExternalDataModel>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("AddEdit", "Form", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="col-sm-3 paddingVarTop">
Form Title<span class="required-symbol"> *</span>
</div>
<div class="col-sm-5">
#Html.TextBoxFor(m => m.Item1.FormTitle, new { #maxlength = "100", #class = "form-control" })
</div>
<div class="col-sm-4">
<span class="required-symbol"> #Html.ValidationMessageFor(m => Model.Item1.FormTitle)</span>
</div>
<button type="submit" class="btn btn-primary" id="saveForm"> Save</button>
}
I want to access the FormTitle in controller how to do it. Below code for controller which currently returns null value for FormTitle:
public ActionResult AddEdit(FormModel _Form)
{
string title = _Form.FormTitle;
return RedirectToAction("Index", "Form");
}
First of all sorry for my bad English. I am new to ASP.NET MVC and currently I am doing small "Rent-a-car" project on it.
I want to make a form where administrator of the page can add Cars on page with details like name, year of production and picture. Following some tutorials I made a form to create a car with name and year of production and I made separately a form where administrator can upload a picture of the car.
Now I have two HTML forms with two submit buttons, one for creating a car and second for uploading an image of the car. I want to combine those two forms into one where Administrator could type name of the car, year of production, select a picture which he want's to upload and then submitting all that with one button.
I have no idea how to do that so please review my code below and tell me what changes do I have to make, I will appreciate any help
This is my Car model:
public class Car
{
[Key]
public int CarID { get; set; }
public string Model { get; set; }
public int YearOfProduction { get; set; }
public string Price { get; set; }
public string Photo { get; set; }
public string AlternateText { get; set; }
[NotMapped]
public HttpPostedFileBase File { get; set; } //for image upload
}
This is my Create (car) Action Method in the "Cars" controller:
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Model,YearOfProduction")] Car car)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
This is my Upload (image of the car) Action Method in the "Cars" controller:
[HttpPost]
public ActionResult Upload(Car picture)
{
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
picture.File.SaveAs(path);
}
return RedirectToAction("Index");
}
This is my HTML form for creating a car:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Car</h4>
<hr/>
#Html.ValidationSummary(true, "", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(model => model.Model, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.Model, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.Model, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.YearOfProduction, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.YearOfProduction, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.YearOfProduction, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
</div>
}
This is my HTML form for uploading an image of the car:
#using (Html.BeginForm("Upload", "Cars", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>File:</td>
<td><input type="file" name="File" id="File"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Upload"/></td>
</tr>
</table>
}
You can use the command name in your <input> tag as shown below:
#Html.BeginForm()
{
#Html.AntiForgeryToken()
<!-- Your Razor code for the input form goes here -->
<!-- Now your Upload button -->
<table>
<tr>
<td>File:</td>
<td><input type="file" name="File" id="File"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="commandName" value="Upload"/></td>
</tr>
</table>
<!-- Finally, your form submit button -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="commandName" value="Create" class="btn btn-default"/>
</div>
</div>
}
And in your controllers' action method accept it as a parameter.
public ActionResult Create(Car car, string commandName)
{
if(commandName.Equals("Create"))
{
// Call method to create new record...
}
else if (commandName.Equals("Upload"))
{
// Call another method to upload picture..
}
}
If you research, there is another elegant generic solution, where you can just apply a multiple-button attribute on the Action method and it will automatically call the controller action. However, you need to be careful about getting values in that case ( *It's out of scope for this question). You can refer: How do you handle multiple submit buttons in ASP.NET MVC Framework?
You can add the input file field in the other form and merge both action method's code into one.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Car</h4>
<hr/>
#Html.ValidationSummary(true, "", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(model => model.Model, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.Model, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.Model, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.YearOfProduction, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.YearOfProduction, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.YearOfProduction, "", new {#class = "text-danger"})
</div>
</div>
<div>
<label>File</label>
<input type="file" name="File" id="File"/>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
</div>
}
and the action method, save the file to disk and store the filename in your db table records so that you can retrieve this file later (for view purposes).
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Car car)
{
if (ModelState.IsValid)
{
if (car.File.ContentLength > 0)
{
var fileName = Path.GetFileName(car.File.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
picture.File.SaveAs(path);
car.Photo = fileName;
}
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
Also, you may consider generating a unique file name so that you won't overwrite the existing files on disk if user is updating the file with same name for different records.
You can use this code to generate a random file name.
var fileName = Path.GetFileName(car.File.FileName);
fileName = Path.GetFileNameWithoutExtension(fileName) +
"_" +
Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName);
var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
//continue with saving
Also remember, the best way to prevent over posting is by using a view model with properties needed for your view. You can create a view model and use that to transfer data from view to action method. In that case, you can totally remove the property (decorated with [NotMapped] from your entity class)
Have a look at this.
It looks like it might help you combine your two forms (and controller actions) into one
I'm going to create profile for my users in ASP.Net MVC application. Users creation controller is something like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserProfileViewModel userViewModel)
{
if (ModelState.IsValid)
{
....
}
return View(userViewModel);
}
Besides, each user model got several properties including one photo. Everything goes well till I want to add an input field to accept photo.
#Html.TextBoxFor(model => model.ImageUrl, new { type = "file" })
And I add below field to UserProfileViewModel:
[Display(Name = "Profile Photo")]
public HttpPostedFileBase ImageUrl { get; set; }
Among snippets to upload a photo and answers to my previous question, it seems uploading photo was considered as a separate task. i.e. I need an individual form and controller to upload a photo (like first part of this answer).
I want to know are there any methods that I can create whole user profile in one form and pass its photo to the same controller (which included photo in UserProfileViewModel)?
I need to note I don't know to use jQuery or AJAX and I want to use standard HTML helpers for this task.
Update: My View Looks like this:
#model ProjectManager.Models.UserProfileViewModel
#{
ViewBag.Title = "Create";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User Profile</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Age)
#Html.ValidationMessageFor(model => model.Age)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageUrl, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ImageUrl, new { type = "file" })
#Html.ValidationMessageFor(model => model.ImageUrl)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="ثبت" class="btn btn-default" />
</div>
</div>
</div>
}
<div class="rtl text-right">
#Html.ActionLink("Back To List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
File inputs are not sent in the request unless your form element contains the enctype = "multipart/form-data" attribute. Change the view code to
#using (Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
....
}
All i have got, your question is I want to know are there any methods that I can create whole user profile in one form and pass its photo to the same controller (which included photo in UserProfileViewModel)?
Yes. It is possible. If you overwrite the form as Stephen Muecke said, you should get the photo with viewmodel. If you get null in viewmodel, you can retrieve the file(photo) from the request also.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserProfileViewModel userViewModel)
{
if (ModelState.IsValid)
{
HttpPostedFileBase fileUploadObj= Request.Files[0];
//for collection
HttpFileCollectionBase fileUploadObj= Request.Files;
....
}
return View(userViewModel);
}
Hope this helps :)
You need to use an BeginForm() that allows you to add htmlAttributes, and because you need to add
new {enctype = "multipart/form-data" }
#using (Html.BeginForm("UserProfileViewModel ", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UserProfileViewModel(UserProfileViewModel userViewModel)
{
if (ModelState.IsValid)
{
HttpPostedFileBase fileUpload= Request.Files[0];
//for collection
HttpFileCollectionBase fileUpload= Request.Files;
....
}
I am working on a MVC web application and not sure where I should add my code to handle button clicks. I have a cshtml view that is being rendered by a controller. When the view is displayed I need to handle several buttons that are being displayed - such print, email, etc. Where should I add my code to handle these and can you give me an example on how to implement it?
<input id="save-button" type="submit" class="btn btn-primary" onclick="submitOrder();" value="Print Order" />
The submitOrder() call is what I need to handle.
1.If your button is not posting back to a form you can call the controller like this:
<input type="button" value="Something" onclick="location.href='#Url.Action("ActionName", "ControllerName")'" />
there are several overloads to this method, some accepting many more parameters.
2.If you are posting back a form and your input button is within that form, then your input button will post back to the controller.
The login page in the default mvc application has examples of both of the 2 options I've mentioned above.
Here's a part of that page:
<section id="loginForm">
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
<p>
#Html.ActionLink("Register", "Register") if you don't have a local account.
</p>
}
</section>
You also have several options to call a controller using JQuery Ajax. That's a little more sophisticated, though.