Passing model data from view to controller and using its values
I am trying to send data from a view and use it in a controller to generate a filename for a file upload function that I am working on, my code is below.
controller
// GET: File
[Authorize(Roles = "Admin, Lecturer")]
public ActionResult Index()
{
foreach (string upload in Request.Files)
{
if (Request.Files[upload].FileName != "")
{
string path = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/uploads/";
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(path, filename));
}
}
return View();
}
Model
public class UploadModel
{
[Required(ErrorMessage = "Course is required")]
public string Course { get; set; }
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
public string Uploader { get; set; }
}
View
<div class="uploadContainer">
<table>
<tr>
<td>Title :</td>
<td colspan="2" class="editPostTitle">
@Html.TextBoxFor(tuple => tuple.Item1.Title, new { @class = "uploadTitleInp" })
@Html.ValidationMessageFor(tuple => tuple.Item1.Title)
</td>
</tr>
<tr>
<td>Course :</td>
<td>
@{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (var cat in courses)
{
listItems.Add(new SelectListItem
{
Text = cat.Course.Name,
Value = cat.Course.Name
});
}
}
@Html.DropDownListFor(tuple => tuple.Item1.Course, listItems, "-- Select Status --")
@Html.ValidationMessageFor(tuple => tuple.Item1.Course)
</td>
</tr>
<tr>
<td>File :</td>
<td>
<input type="file" name="FileUpload1" id="fileUpload" required />
</td>
</tr>
<tr>
<td></td>
<td>
<input id="btnUploadFile" type="button" value="Upload File" />
</td>
</tr>
</table>
</div>
This method is responsible for placing the file uploaded to the directory. What I want to do is create a filename by doing something like this.
string filename = model.Title + " - " + model.Course;
I usually know how to achieve this when using the db to store the data, but since I don't store the files loaded in the db, then I really don't know how to pass the model data to the controller so that I can use the values entered by the user to generate the file name. I am relatively new to this framework and languages, so any help and pointers would be greatly appreciated.
Thanks in advance!
source to share
You need to pass data back through your model to a separate controller method. This can be implemented as follows (I've simplified your code a bit, but the general implementation should work):
public class UploadViewModel
{
public string Course { get; set; }
public string Title { get; set; }
}
Your GET action:
public ActionResult Index()
{
return View(new UploadViewModel());
}
Then, in your opinion, add the model and use it on the form so that the data is bound to your model. This can then be sent back to your controller.
@model UploadViewModel
@using(Html.BeginForm())
{
Course: @Html.TextBoxFor(s=>s.Course)
Title: @Html.TextBoxFor(s=>s.Title)
<input type="submit" value="Save file" />
}
Now get the values through the HttpPost action method in your controller:
[HttpPost]
public ActionResult Index(UploadViewModel model)
{
//You can use model.Course and model.Title values now
}
source to share
There are two ways to send data controller
. You must match the data sent toController method
Using the Ajax Post method:
A portable javascript object will be created. the object object name must match the model property name.
var objAjax = new Object();
objAjax.Course = 'newCourse'; // Model prop is string type so this value must be string.
objAjax.Title = 'newTitle';
$.ajax('@Url.Action("MethodName", "ControllerName")', {
type: 'POST',
data: JSON.stringify(objAjax),
contentType: "application/json",
datatype: "json",
traditional: true,
success: function (returnData) {
// Do something when get success
},
error: function () {
// Do something when get an error
}
});
[HttpPost]
public ActionResult Index(UploadViewModel model)
{
//do someting
}
Using the FormPost method
Html.BeginFom
send all data in the model to the controller when the submit button is clicked
Forexample
@using(Html.BeginForm())
{
<div>
// Your code
<div>
<input type="submit" value="Go" />
</div>
</div>
}
[HttpPost]
public ActionResult Index(UploadViewModel model)
{
//do someting
}
source to share