简体   繁体   中英

How does @Html.ListBox() and @Html.DropDownList() keep the state in asp.net mvc?

Controller:

public class HomeController : Controller
            {
                //
                // GET: /Home/
                public ActionResult Index()
                {   
                    return View();
                }
                [HttpPost]
                public ActionResult Index(string list1)
                {
                    return View();
                }


            }

View(uses default layout):

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{

    @Html.DropDownList("list1",
                        new SelectList(new[] { "Item 1", "Item 2", "Item 3" }))

    <input type="submit"/>
}
<br />
<br />

After selecting value in DropDownList and submitting the form my application have same state that was before. For example if i had selected "item 3" after pressing "submit" i have selected "item 3". How does it work?

Upd:

I dont want to avoid it, just want to understand how its work.

In your [Post] handler you are not redirecting anywhere and returning a view directly. Hence the values persist because they are still found in the model state.

A common pattern is to redirect to a [Get] handler after a successful Post , in which case values would not persist.

From MVC sources:

SelectExtensions.cs:

.....
    object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));
.....

HtmlHelper.cs:

internal object GetModelStateValue(string key, Type destinationType)
        {
            ModelState modelState;
            if (ViewData.ModelState.TryGetValue(key, out modelState))
            {
                if (modelState.Value != null)
                {
                    return modelState.Value.ConvertTo(destinationType, null /* culture */);
                }
            }
            return null;
        }

Well, it means that Action sends "ModelState" to view and controls(i know that it's not correct definition) use "ModelState" for fill themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM