ASP.NET MVC + Web API Controller + Routing Rule Configuration
Global.asax.cs |
using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Http; namespace NewsWeb { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } } |
\App_Start\WebApiConfig.cs |
using System.Web.Http; namespace NewsWeb { public class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } } |
Form ( View ) – Adv.cshtml |
<h2>Advertisement Add</h2> @using (Html.BeginForm("AdvPost", "api/Form")) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) @Html.EditorForModel("AdvForm") } |
Form ( EditorTemplates ) – AdvForm.cshtml |
@model NewsWeb.Models.News.Advertisement <fieldset> <div class="editor-label"> @Html.LabelFor(model => model.Advertisement_Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Advertisement_Title, null, new { style = "width:100%;" }) @Html.ValidationMessageFor(model => model.Advertisement_Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Advertisement_ImageURL) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Advertisement_ImageURL, new { style = "width:100%;", }) @Html.ValidationMessageFor(model => model.Advertisement_Title) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> |
Web API Controller – \Controllers\FormController.cs |
using System.Web.Http; using NewsBusinessLogic; using NewsWeb.Models.News; using AutoMapper; namespace NewsWeb.Controllers { public class FormController : ApiController { // POST api/ [HttpPost] [ActionName("AdvPost")] public void Post(Models.News.Advertisement adv) { NewsEntity.Advertisement AdvItem = Mapper.Map(adv, new NewsEntity.Advertisement()); AdvertisementServices services = new AdvertisementServices(); services.setAdvertisement(AdvItem); } } } |