0
Model----------------------
public class Test 
{
    [Required(ErrorMessage = "Must Be Select ")]
    public string TestList { get; set; }
}

Controller-----------------
public ActionResult Index(){
    Test test = new Test();

    string code = "11";
    Dictionary<string, string> selectList = new Dictionary<string, string>();
    selectList.Add("33", "33 value");
    selectList.Add("22", "22 value");
    selectList.Add("11", "11 value");
    ViewBag.TestList = selectList.Select(x => new SelectListItem { 
          Text = x.Value, Value = x.Key, Selected = x.Key.Equals(code) 
    }).ToList();

    return View(test);
}

View-----------------------
@model ~~~

@Html.DropDownListFor(model => model.TestList, null, "--SelectThis--")

i use c#, mvc3, razor with jquery.unobtrusive that code are cool but has problem -- html source view

<select name="TestList" id="TestList"></select>
<select name="TestList" id="TestList" data-val=true data-val-required="Must Be Select">

i want second result.. how can i do??

1 Answer 1

1

If you want the second result ensure that this @Html.DropDownListFor helper is inside a form:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(model => model.Code, null, "--SelectThis--")
    <input type="submit" value="OK" />
}

Also passing null as second argument is unlikely something that will work. You probably meant:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        model => model.Code, 
        new SelectList(ViewBag.TestList, "Value", "Text"), 
        "--SelectThis--"
    )
    <input type="submit" value="OK" />
}

and what I would strongly recommend you is the following:

Model:

public class Test 
{
    [Required(ErrorMessage = "Must Be Select ")]
    public string TestList { get; set; }

    public IEnumerable<SelectListItem> TestList { get; set; }
}

Controller:

public ActionResult Index()
{
    var selectList = new Dictionary<string, string>
    {
        { "33", "33 value" },
        { "22", "22 value" },
        { "11", "11 value" },
    };

    var model = new Test
    {
        Code = "11",
        TestList = selectList.Select(x => new SelectListItem 
        {
            Text = x.Value, Value = x.Key
        })
    };
    return View(model);
}

View:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        model => model.Code, 
        new SelectList(Model.TestList, "Value", "Text"), 
        "--SelectThis--"
    )
    <input type="submit" value="OK" />
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'll never get anywhere when you're online :) (Also, I can't believe I forgot the SelectList)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.