如何将数据传递到MVC asp.net的看法? [英] How to pass data to the view in mvc asp.net?

查看:132
本文介绍了如何将数据传递到MVC asp.net的看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我先问一个问题。

在哪里是正确的地方调用加载值列表功能是在视图上显示?

Where is the correct place to call a function that load a list of values to be display on a view?

我创建这样一个控制器

public ActionResult Create()
{
    SeaModel newSea = new SeaModel();

    return View("Season/CreateSea", newSea);
}

//I not quite sure if this should go here or in another place
partial class seaDataContext
{
    public List<string> getSeaSettings()
    {
        var seaSettings = from p in settings
                          where p.setting == "periods"
                          select p.value;

        return seaSettings.ToList<string>();                              
    }
}

该模型是像

public class SeaModel
{
    [Required(ErrorMessage="*")]
    [Display(Name = "Period Name")]
    public string periods { get; set; }    
}

其中创建像

  @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Please correct the following errors.")

        <fieldset>
            <legend>Fields</legend>

            <div class="editor-label">
                @Html.LabelFor(model => model.periods)
            </div>
            <div class="editor-field">
                @Html.Select(model => model.periods, ****My doubt comes here****)
                @Html.ValidationMessageFor(model => model.periods)
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    }

那么,如何以及在哪里我通过getSeaSettings()到视图的回报?

so, How and where do I pass the return of getSeaSettings() to the view?

感谢

推荐答案

最好的做法是做一个选择列表中的模型此下拉列表。

best practice is to make a Selectlist in your Model for this dropdown.

不过,您还可以使用更简单的选择:使用的ViewData

however you also can use the more easy option: using ViewData

 public ActionResult Create()
 {
     SeaModel newSea = new SeaModel();

     ViewData["myDropDown"] = new SelectList(listOfObjects, "valueOfTheObjectLikeID", "NameYouWantToShowInDropdown");

     return View("Season/CreateSea", newSea);
 }

然后

@Html.Select(model => model.periods, ViewData["myDropDown"] as SelectList)

不要在你的[HttpPost]法忘了还填补了可视数据,如果找你验证失败,这样的下拉可以重建。

dont forget in your [HttpPost] method to also fill in the viewdata if you'r validation fails, so the dropdown can be rebuilt.

这篇关于如何将数据传递到MVC asp.net的看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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