简体   繁体   English

将模型数据从View传递到Controller并使用其值

[英]Passing Model data from View to Controller and using its values

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! 提前致谢!

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: 你的GET行动:

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操作方法获取值:

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

There are two different way to send data controller . 发送数据controller有两种不同的方式。 You must match the data you send in the Controller method 您必须匹配在Controller method发送的数据

Using Ajax Post Method : 使用Ajax Post方法:

Will be create transfered object on javascript. 将在javascript上创建转移对象。 object property name must be same to Model property name. 对象属性名称必须与Model属性名称相同。

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 使用FormPost方法

Html.BeginFom send all the data in the model to controller when press the submit button 当按下提交按钮时, Html.BeginFom将模型中的所有数据发送到控制器

ForExample 例如

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

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM