Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将模型数据从视图传递到控制器并使用其值_C#_Asp.net Mvc_Razor_Asp.net Mvc 5 - Fatal编程技术网

C# 将模型数据从视图传递到控制器并使用其值

C# 将模型数据从视图传递到控制器并使用其值,c#,asp.net-mvc,razor,asp.net-mvc-5,C#,Asp.net Mvc,Razor,Asp.net Mvc 5,我正在尝试从视图发送数据,并在控制器中使用它为我正在处理的上载文件功能构造文件名,我的代码如下 控制器 // GET: File [Authorize(Roles = "Admin, Lecturer")] public ActionResult Index() { foreach (string upload in Request.Files) { if (Request.Files[upload].

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

控制器

    // 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>
我通常知道在使用db存储数据时如何实现这一点,但由于我没有存储在db中上载的文件,因此我真的不知道如何将模型数据传递给控制器,以便使用用户输入的值来构造文件名。我对这个框架和语言还比较陌生,所以任何帮助和指点都会非常感激


提前谢谢

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

您的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" />
}

有两种不同的方式发送数据
controller
。您必须匹配在
控制器方法中发送的数据

使用Ajax Post方法:

<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>
将在javascript上创建传输的对象。对象属性名 必须与模型属性名称相同

使用FormPost方法

Html.BeginFom
在需要时将模型中的所有数据发送给控制器 按提交按钮

例如

@使用(Html.BeginForm())
{
//你的代码
}
[HttpPost]
公共操作结果索引(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]
public ActionResult Index(UploadViewModel model)
{
    //You can use model.Course and model.Title values now
}
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(Html.BeginForm())
{
    <div>
         // Your code 

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


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