在输入文本框中获取值并将其发送到控制器

时间:2012-07-09 21:36:16

标签: asp.net-mvc-3 jquery

有哪些方法可以将输入值文件名呈现并发送给控制器:

<div id="fileuploaddiv" class="fileuploaddivclass">
<form action="@Model.FormAction" method="@Model.FormMethod"
    enctype="@Model.FormEnclosureType">
<input type="hidden" name="key" value="uploads/${filename}" id="filename" />
<input type="hidden" name="AWSAccessKeyId" value="@Model.AWSAccessKey" />
<input type="hidden" name="Content-Type" value="image/jpeg">
<div>
    Please specify a file, or a set of files:
    <input type="file" name="file" />
</div>
<input type="submit" value="Upload" />
</form>
</div>

1 个答案:

答案 0 :(得分:1)

你需要查看一些MVC3约定(我推荐NerdDinner作为一个很好的入门教程),但这里有一个类似于你想做的方法:

@Model YourViewModel
<div id="fileuploaddiv" class="fileuploaddivclass">
    @using(Html.BeginForm(Model.FormAction, Model.FormController, FormMethod.Post)
        @Html.HiddenFor(model.key => ${fileName})
        @Html.HiddenFor(model.AWSAccessKeyID)
        @Html.HiddenFor(model.Content-Type)
        @<input type="submit" value="Submit My Form" />
    @Html.EndForm()
</div>

你的模型看起来像(我在这里很困惑,因为你似乎动态设置了控制器和动作,这很不寻常):

public class YourViewModel
{
     public string FormAction { get; set; }
     public string FormController { get; set; }
     public int AWSAccessKeyID { get; set; }
     public string Content-Type { get; set; }
}

现在转到控制器:

[HttpGet]
public ActionResult WhateverControllerName()
{
    YourViewModel yvm = new YourViewModel();
    //Initalize viewmodel here
    Return view(yvm);
}

[HttpPost]
public ActionResult WhateverControllerName(YourViewModel yvm)
{
    if (ModelState.IsValid) {
        //Do whatever you want here. Perhaps a redirect?
    }
    return View(yvm);
}

注意:我在语法上是垃圾,所以你必须检查这一点,但Visual Studio应该告诉你什么有效。