如何在ASP.NET MVC创建视图中添加一些自己的表单?

时间:2012-07-02 07:39:51

标签: asp.net-mvc

我遇到了问题,我创建了一个控制器和一个用于从特定模型添加新项目的视图。视图看起来像:

@modelModels.UserItem

@{
    ViewBag.Title = "New";
}

<h2>New</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)  
    <fieldset>
        <legend>Device</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

和控制器:

[HttpPost]
public ActionResult New(UserItem useritem)
{
    if (ModelState.IsValid)
    {
        db.UserItems.AddObject(useritem);
        db.SaveChanges();

        return RedirectToAction("Index");
    }

    return View(useritems);
}

我想如何在视图中添加下拉列表,如下所示:

<select id="Select1">
    <option>MARS</option>
</select>

如何在控制器中提交表单后访问表单中的数据?

3 个答案:

答案 0 :(得分:6)

拥有您网页的视图模型,此视图模型将在您的视图中使用。因此,只包含您真正需要的模型中的字段。在Get action中,您应该创建此视图模型并从模型中获取所需的属性,并将它们映射到视图模型。

public class UserItemViewModel
{
    /* Properties you want from your model */
    public string Property1                           { get; set; }
    public string Property2                           { get; set; }
    public string Property3                           { get; set; }

    /* Property to keep selected item */
    public string SelectedItem                        { get; set; }
    /* Set of items to fill dropdown */
    public IEnumerable<SelectListItem> SelectOptions  { get; set; }

    /* Fill the SelectListHere. This will be called from index controller */
    public void FillOptions()
    {
        var items = new[] { "Mars", "Venus" }.
              Select(x => new SelectListItem { Value = x, Text = x });

        SelectOptions= new SelectList(items, "Value", "Text");
    }
}

更改控制器以接收ViewModel而不是模型本身。

[HttpPost]
public ActionResult New(UserItemViewModel useritem)
{
    /* Repopulate the dropdown, since the values are not posted with model. */
    userItem.FillOptions();

    if (ModelState.IsValid)
    {
        /* Create your actual model and add it to db */

        // TODO: Map your properties from model to view model.
        // Let's say you created a model with name userItemModel
        db.UserItems.AddObject(userItemModel);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(useritem);
} 

您可能需要更改索引视图控制器。(填充下拉列表)

[HttpGet]
public ActionResult Index()
{
    /* Create new viewmodel fill the dropdown and pass it to view */
    var viewModel = new UserItemViewModel();
    viewModel.FillOptitons();

    //TODO : From your model fill the required properties in view model as I mention.

    return View(viewModel);
} 

你的观点,

/* Strongly typed view with viewmodel instead of model itself */
@modelModels.UserItemViewModel

/* This is the dropdown */
@Html.DropDownListFor(m => m.SelectedItem, Model.SelectOptions)

答案 1 :(得分:0)

  1. 将该属性添加到模型中
  2. 使用内置EditorFor(优先)或手写的html为该属性生成客户端输入。
  3. 通过在用户提交表单时检查该属性来访问提交的值

答案 2 :(得分:0)

我喜欢emre建议使用viewModel,我觉得这是你问题的最佳解决方案,但是如果你不想这样做(你必须有一个非常好的理由,因为它是最好的)并且仍然想要一种直接访问表单值的方法,您可以随时使用:         var x = Request [“myFiledName”]; 在你的控制器内部,以获得表单传递的值。