Friday, May 11, 2012

Controllers - In general

  • Data can be passed between the Controller and the View using the ViewBag - a dynamic data that has no predefined properties or by setting the Model for the View
  • TIP: Right-click on the Controllers folder of the project and choose Add | Controller
  • By convention, the name of the Controller is suffixed with the word Controller
  • To add an Action, implement a public method for the Controller

public class MyAppController : Controller
{

  // GET: hostname/
  public string Index()
  {
    return "When MyAppController controller and Index 
actions are specified as the default route, Index action can be 
accessed by visiting the root of the website";
  }

  // GET: hostname/MyAppController/Welcome
  public string Welcome()
  {
    return "Welcome to my site";
  }

  // GET: hostname/MyAppController/GetArticle?name=mvc
  public string GetArticle(string name)
  {
    return "MVC model binding retrieves the value 
for name from the query string and passes it as 
argument to GetArticle. You passed: '"  + 
HttpUtility.HtmlEncode(name) + "'";
  }

  public ActionResult SomeView()
  {
    VeewBag.SomeData = "This data is available to the View in ViewBag";

    return View(); // creates and returns view named "SomeView"
                   //  from the corresponding view subfolder
                   // An overload of View() allows explicit name
                   //  of the desired view
  }

}

// POST: hostname/MyAppController/AddData
[HttpPost]
public ActionResult Edit(FormCollection fc, MyDataType data)
{
  // adding FormCollection argument allows us to avoid conflict with
  //   GET version of this method. We can also use a different
  //   C# method name
  //     but expose it with the same name as external API with a
  //     method attribute - [HttpPost, ActionName("Edit")]
  // Run the validation provided as data annotations of MyDataType
  if (ModelState.IsValid)
  {
    ...
    return RedirectToAction("Index");
  }
  // valid failed - echo the form back
  return View(data);
}

// Handling non-existent data
// GET
public ActionResult Edit(int id=0)
{
  // set default value of id to 0
  var data = GetData(id);
  if (data == null)
    return HttpNotFound();
  return View(data);
}

// Creating SelectList for use by DropDown
var someList = new List();
// Dropdown in view uses the ListData from the ViewBag
ViewBag.ListData = new SelectList(someList);