Passing Model data from View to Controller and using its values

南楼画角 提交于 2019-12-06 06:53:14

问题


I'm trying to send data from the view and use it in the controller to construct a filename for an upload file feature 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 that is uploaded into the directory. What I want to be able to do is create a file name by doing something like this.

string filename = model.Title + " - " + model.Course;

I usually know how to achieve this when using a db to store data but since I am not storing the files that are uploaded in a db then I don't really know how to pass the model data to the controller so I can use the values that have been entered by the user to construct the file name. I am relatively new to this framework and languages so any help and pointers would be greatly appriciated.

Thanks In advance!


回答1:


You have to pass the 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 view add the model and use it in the form, so that the data will be bound to your model. This can then be send 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 a HttpPost action method in your controller:

[HttpPost]
public ActionResult Index(UploadViewModel model)
{
    //You can use model.Course and model.Title values now
}



回答2:


There are two different way to send data controller. You must match the data you send in the Controller method

Using Ajax Post Method :

Will be create transfered object on javascript. object property name must be same to 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 something with the result
    }

Using FormPost Method

Html.BeginFom send all the data in the model to controller when press the submit button

ForExample

@using(Html.BeginForm())
{
    <div>
         // Your code 

        <div>
            <input type="submit" value="Go" />
        </div>
    </div>
}


[HttpPost]
public ActionResult Index(UploadViewModel model)
{
    //do someting
}


来源:https://stackoverflow.com/questions/43495717/passing-model-data-from-view-to-controller-and-using-its-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!