将模型数据从视图传递到控制器并使用其值 [英] Passing Model data from View to Controller and using its values

查看:29
本文介绍了将模型数据从视图传递到控制器并使用其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从视图发送数据并在控制器中使用它来为我正在处理的上传文件功能构建文件名,我的代码如下.

控制器

//获取:文件[授权(角色=管理员,讲师")]公共 ActionResult 索引(){foreach(Request.Files 中的字符串上传){if (Request.Files[upload].FileName != ""){字符串路径 = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/uploads/";字符串文件名 = Path.GetFileName(Request.Files[upload].FileName);Request.Files[上传].SaveAs(Path.Combine(path, filename));}}返回视图();}

模型

公共类 UploadModel{[必需(ErrorMessage = "课程是必需的")]公共字符串课程{获取;放;}[必填(ErrorMessage = "需要标题")]公共字符串标题{获取;放;}公共字符串上传者 { 获取;放;}}

查看

<表格><tr><td>标题:</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>课程:</td><td>@{列表listItems = new List();foreach(课程中的 var cat){listItems.Add(new SelectListItem{文字 = cat.Course.Name,值 = cat.Course.Name});}}@Html.DropDownListFor(tuple => tuple.Item1.Course, listItems, "-- 选择状态--")@Html.ValidationMessageFor(tuple => tuple.Item1.Course)</td></tr><tr><td>文件:</td><td><input type="file" name="FileUpload1" id="fileUpload" required/></td></tr><tr><td></td><td><input id="btnUploadFile" type="button" value="上传文件"/></td></tr>

该方法负责将上传的文件放入目录中.我想要做的是通过做这样的事情来创建一个文件名.

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

我通常知道如何在使用 db 存储数据时实现这一点,但由于我没有存储在 db 中上传的文件,所以我真的不知道如何将模型数据传递给控制器​​,所以我可以使用用户输入的值来构造文件名.我对这个框架和语言比较陌生,所以任何帮助和指针都会非常有用.

提前致谢!

解决方案

您必须将数据通过模型传递回单独的控制器方法.这可以按如下方式实现(我已经稍微简化了您的代码,但一般实现应该可行):

公共类 UploadViewModel{公共字符串课程{获取;放;}公共字符串标题{获取;放;}}

您的 GET 操作:

public ActionResult Index(){返回视图(新上传视图模型());}

然后在您的视图中添加模型并在表单中使用它,以便将数据绑定到您的模型.然后可以将其发送回您的控制器.

@model UploadViewModel@using(Html.BeginForm()){课程:@Html.TextBoxFor(s=>s.Course)标题:@Html.TextBoxFor(s=>s.Title)<input type="submit" value="保存文件"/>}

现在通过控制器中的 HttpPost 操作方法获取值:

[HttpPost]公共 ActionResult 索引(UploadViewModel 模型){//您现在可以使用model.Course和model.Title值}

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:

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
}

这篇关于将模型数据从视图传递到控制器并使用其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆