Asp.net mvc select list

狂风中的少年 提交于 2019-12-21 20:34:00

问题


I need to create a select list, preserving the state, which is not part of the model passed to the view. I suppose I should be using a ViewBag to pass a List to the View ? Any advise on implementation and how to preserve the state of the select list (how do I pass the selected value back to action and to the view again (possible ways of doing this) ?

The Action as of now:

public ActionResult Images(string x, string y)
{
//some code 

ContentPage cp = this.ContentPage;

return View(cp);
} 

//Post to action with same name:
[HttpPost]
public ActionResult Images(string someParameter)
 {

    ContentPage cp = this.ContentPage;

    return View(cp);
 }

The view as of now :

@model ContentPage
@{
ViewBag.Title = "Images";
CmsBaseController controller = (this.ViewContext.Controller as CmsBaseController);
}
@using (Html.BeginForm())
{ 
<div>

//This should go to List<SelectListItem> as I understand
<select name="perpage" id="perpage" onchange='submit();'>
           <option value="1">1</option>
           <option value="2">2</option>
           <option value="3">3</option>

</select>
</div>
}

Thank you!!!


回答1:


Have you taken a look at this SO question? The answer there looks like it would do the trick if you wanted to use ViewBag/ViewData to pass in that list.

That said, why not just create a quick viewmodel and store it there? It really is a simple way to go.

I don't know what your ContentPage model is but you could certainly make a ContentPageViewModel that has whatever stuff (including the values for the select list) that is necessary for the page.


Example:

It would easy enough, for example, to have a property on the viewmodel to hold the selection and a property that holds some enumeration of possible values. Something like this:

public class MyViewModel
{
   ...

   public int SelectedId { get; set; }

   ...

   public IEnumerable<Choice> Choices { get; set; }
}

where Choice, in my example, is a class that has two properties, one that holds some identifier and the other the text to display. Something like this:

public class Choice
{
   public int Id { get; set; }
   public string Text { get; set; }
}

And then you could just have, perhaps, a DropDownListFor which handles the display/selection work for you. Something like this:

@model MyViewModel

@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.Choices, "Id", "Text"), "Choose... ")

Back in your controller's action, the viewmodel's SelectedId will get populated with the corresponding Id for the Choice picked view the dropdown.



来源:https://stackoverflow.com/questions/7208924/asp-net-mvc-select-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!