Friday, January 24, 2014

How to bind Dropdownlist in mvc.

Home ontroller

public ActionResult Register()
{
ViewBag.stateList = getState(); 
return View();
}
[HttpPost]
public ActionResult Register( Models.Register rn, HomeController ddlListPostData)
{
if (ModelState.IsValid)
{
HomeController ddlList = new HomeController() { istateid = ddlListPostData.istateid };
}
ViewBag.stateList = getState();
return View(rn);
}

public virtual string istateid { get; set; }
public SelectList getState()
{
db_TestNewEntities _db = new db_TestNewEntities();
IEnumerable<SelectListItem> stateList = (from m in _db.tblCountry select m).AsEnumerable().Select(m => new SelectListItem()
{ Text = m.Name, Value = m.CountryID.ToString() });
return new SelectList(stateList, "Value", "Text", istateid);
}


Model (register.cs)
public class Register

{


[Required]

[Display(Name = "UserName")]
public String UserName { get; set; }


[Required]

[DataType(DataType.Password)]

[Display(Name = "Password")]
public string Password { get; set; }

internal bool IsValid(string p, string p_2)

{

if (p == "sahil")

return true;

else

return false;

}

}



View (Register.cshtml)

@model MvcApplication1.Models.Register

@{ ViewBag.Title = "Register";}

<h2>Register</h2>

@using (Html.BeginForm())




{
 
@Html.AntiForgeryToken()

@Html.ValidationSummary(true, "Login failed. Check your login details.");

<fieldset >

<legend>Login </legend>

<div>

<div>

<div>Country</div>

<div>@Html.DropDownList("istateid", (SelectList)ViewBag.stateList, "--Choose Your State--", new { id = "State" })</div>

<div> @Html.ValidationMessage("State", "*")</div>

</div>

<div>

<div>@Html.LabelFor(m=>m.UserName)</div>

<div> @Html.TextBoxFor(m=>m.UserName)</div>

<div> @Html.ValidationMessageFor(m=>m.UserName)</div>

</div>

<div>

<div>@Html.LabelFor(m=>m.Password )</div>

<div> @Html.TextBoxFor(m => m.Password)</div>

<div> @Html.ValidationMessageFor(m => m.Password)</div>

</div>

<div>

<div><input type="submit" id="btnSubmit" name="a" value="Submit" /> </div>

</div>

</div>

</fieldset>



}

No comments:

Post a Comment