【问题标题】:Passing Model data from View to Controller and using its values将模型数据从视图传递到控制器并使用其值
【发布时间】:2017-09-15 16:22:45
【问题描述】:

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

控制器

    // 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();
    }

型号

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; }
}

查看

<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>

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

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

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

提前致谢!

【问题讨论】:

标签: c# asp.net-mvc razor asp.net-mvc-5


【解决方案1】:

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

public class UploadViewModel
{    
    public string Course { get; set; }
    public string Title { get; set; }
}

您的 GET 操作:

public ActionResult Index()
{
    return View(new UploadViewModel());
}

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

@model UploadViewModel
@using(Html.BeginForm())
{
    Course: @Html.TextBoxFor(s=>s.Course)
    Title: @Html.TextBoxFor(s=>s.Title)
    <input type="submit" value="Save file" />
}

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

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

【讨论】:

  • 谢谢,您已经解决了传递数据的问题。但是,我仍然无法弄清楚如何使用自定义文件名保存正在上传的文件,但我想这完全是另一个问题!
  • @Plumbus 很高兴听到!我现在没有足够的信息来解决这个问题。我认为最好写一个单独的问题。
【解决方案2】:

有两种不同的方式来发送数据controller。您必须匹配您在Controller method中发送的数据

使用 Ajax Post 方法:

将在 javascript 上创建传输对象。对象属性名称 必须与模型属性名称相同。

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
    }

使用 FormPost 方法

Html.BeginFom 将模型中的所有数据发送到控制器时 按下提交按钮

举例

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

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


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多