MVC Learning Series -- ActionResult extension, mvcactionresult
First, MVC is highly scalable.
I started with the extension of ActionResult, because we know that Microsoft ActionResult and its subclass cannot satisfy all returned values.
For example, I need to return XML.
Therefore, now I extend XMLResult to inherit ActionResult.
Step 1: Create an XmlResult
1 public class XmlResult:ActionResult 2 { 3 private object _data; 4 5 public XmlResult(object data) 6 { 7 this._data = data; 8 } 9 public override void ExecuteResult(ControllerContext context)10 {11 var serializer = new XmlSerializer(_data.GetType());12 var reponse = context.HttpContext.Response;13 reponse.ContentType = "text/xml";14 serializer.Serialize(reponse.Output, _data);15 }16 }
Step 2: Create a StudentViewModel class for demonstration
1 public class StudentViewModel2 {3 public string ID { get; set; }4 public string Name { get; set; }5 public string Gender { get; set; }6 }
Step 3: Add GetXmlResult in HomeController
1 public XmlResult GetXmlResult()2 {3 StudentViewModel viewModel = new StudentViewModel();4 viewModel.ID = "1";5 viewModel.Name ="Zhangsan";6 viewModel.Gender = "Man";7 8 return new XmlResult(viewModel);9 }
Step 4: Test
Enter Home/GetXmlResult in IE