Tuesday, July 16, 2013

MVC Controls

Static Binding of Dropdown list:
<p>
Will you attend?

@Html.DropDownListFor(x => x.WillAttend, new[] {
new SelectListItem() {Text = "Yes, I'll be there",
Value = bool.TrueString},
new SelectListItem() {Text = "No, I can't come",
Value = bool.FalseString}
}, "Choose an option")

</p>

Dynamic Binding of Dropdown list:



Model:
public class IndexModel
{
public IEnumerable<SelectListItem> JobNames {get;set;}
}

Controller:
public ActionResult Index(IndexModel model)
 {
           
  IEnumerable<SelectListItem> items = from item in edmx.JobNames
                                      select new SelectListItem
                                      {
                                                        Text = item.JobName1,
                                                        Value = SqlFunctions.StringConvert((double)item.JobId)
                                                    };
                model.JobNames = items;
}







Dynamic Binding of Dropdown list:




Controller:
var DirectorsList = new List<SelectListItem>();

        var DirQuery = from d in db.Directors select d;
        foreach (var d in DirQuery)
        {
            DirectorsList.Add(new SelectListItem { Value = d.ID.ToString(), Text = d.Name });
        }
        ViewBag.Directors = DirectorsList;

View:
@Html.DropDownListFor(model => model.Director, ViewBag.Directors as List<SelectListItem>, "All")



Static Binding of Radiobuttonlist
View:
@model Account
@{
    ViewBag.Title = "Create Account";
}
@using ( Html.BeginForm() )
{
    <div>
        <span>Do you agree to the Terms and Conditions?</span>
        <br />
        @Html.RadioButtonFor( model => model.TermsAndConditions, true, new { id = "TermsAndConditions_true" } )
        <label for="TermsAndConditions_true">Yes</label>
        <br />
        @Html.RadioButtonFor( model => model.TermsAndConditions, false, new { id = "TermsAndConditions_false" } )
        <label for="TermsAndConditions_false">No</label>
        <br />
        @Html.ValidationMessage( "TermsAndConditionsAgreement" )
    </div>
    <div>
        <input id="CreateAccount" type="submit" name="submit" value="Create Account" />
    </div>
}

Model:
public class Account
{
    public bool TermsAndConditions { get; set; }
    //other properties here.
}

Controller:
public ActionResult CreateAccount()
{
    //this default instance will be used to pre-populate the form, making the "No" radio button checked.
    var account = new Account
    {
        TermsAndConditions = false
    };

    return View( account );
}

//This handles the POST request.
[HttpPost]
public ActionResult CreateAccount( Account account )
{
    if ( account.TermsAndConditions )
    {
        //TODO: Other validation, and create the account.
        return RedirectToAction( "Welcome" );
    }
    else
    {
        ModelState.AddModelError( "TermsAndConditionsAgreement", "You must agree to the Terms and Conditions." );
        return View( account );
    }          
}

public ActionResult Welcome()
{
    return View();
}
BONUS: You'll notice that I added a little extra feature to the radio buttons. Rather than just use plain text for the radio button labels, I used the HTML label element with the for attribute set to the IDs of the each radio button. This lets users click on the label to select the radio button instead of having to click on the radio button itself. This is standard HTML. For this to work I had to set manual IDs on the radio buttons, otherwise they would both get the same ID of just "TermsAndConditions", which wouldn't work.
1.var account = new Account
    {
        TermsAndConditions = false
    };

2. Account obj=new Account();
  obj. TermsAndConditions=false;
3. public ActionResult SomeForm()
   {
    return View(new SomeModel { TermsAndConditions = false });
   }


Selecting Radiobutton by default
@Html.RadioButtonFor(model => model.TermsAndConditions, "False", new { Checked = "checked" })

Note: All is ok if the user completes the form without any errors. However,  if I do server side validation and the page is refreshed,  I lose the selection that the user made for the radio button  and the selected radio goes back to the default false field.

http://stackoverflow.com/questions/5768274/correct-way-to-bind-an-mvc3-radiobutton-to-a-model