طريقة عامة لكل الرأي؟ ActionResult الافتراضية وطرق في ASP.MVC
-
21-08-2019 - |
سؤال
وأنا تجريب ASP.NET MVC والطرق.
ويبدو قوات MVC لي أن أضيف أسلوب عمومي إلى وحدة تحكم في أي وقت أريد إنشاء طريقة عرض. على سبيل المثال:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
//... a public method for every view.. :(
}
وأنا لا أريد أن إنشاء أسلوب العام للكل عرض. افتراضيا، أريد سلوك "العودة مشاهدة ()" لجميع وجهات النظر في النظام، ما لم ينص على خلاف ذلك.
وعلى سبيل المثال، HTTP GET:
site.com/about site.com/features site.com/ site.com/testimonials site.com/contact-us
وكما هو عليه الآن، وأود أن أضيف:
HomeController.About()
HomeController.Features()
HomeController.Index()
HomeController.Testimonials()
HomeController.ContactUs()
وكل نتيجة في "عودة عرض ()". هذه هي مشكلتي، وأنا أحاول للقضاء على خلق أساليب العمل العامة وجهات النظر بسيطة.
لوجهات النظر التي تتطلب معالجة إضافية، مثل صفحة الاتصال بنا على وظيفة HTTP إلى:
site.com/contact-us
وأود أن أضيف على وجه التحديد الأسلوب في وحدة تحكم لإرسال رسالة SMTP.
وفيما يلي مثال أكثر إيجازا من ما أحاول القيام به:
public class HomeController{
public ActionResult ShowBasicView(){
//HTTP GET:
//site.com/about
//site.com/features
//site.com/
//site.com/testimonials
//All URLs above map to this action
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactUs(FormCollection data){
//HTTP POST:
//site.com/contact-us
//POST URL maps here.
SmtpClient.Send(new MailMessage()) //etc...
return View()
}
}
وشكرا، براين
المحلول
والمشكلة المحتملة مع وجود ShowBasicView من تحرير الخاص بك هو أنه نظرا لالأسلاك الضمني في وجهات النظر، كل هذه عناوين ستعطي نفس وجهة النظر، وهي:
<اقتباس فقرة>\ المشاهدات \ الرئيسية \ ShowBasicView.aspx
اقتباس فقرة>والآن، قد يكون هذا ما تريد، وعلى الرغم من انها ربما غير مرجح.
هل يمكن ربما وضع هذا الأمر من خلال وجود الطريق مثل:
routes.MapRoute(
"ShowBasic",
"{id}",
new { controller = "Home", action = "ShowBasicView", id = "home" }
);
وتعديل وحدة التحكم الخاصة بك ل:
public class HomeController: Controller{
public ActionResult ShowBasicView(string pageName){
// Do something here to get the page data from the Model,
// and pass it into the ViewData
ViewData.Model = GetContent(pageName);
// All URLs above map to this action
return View();
}
}
وبدلا من ذلك، إذا تم ضمنية المحتوى في وجهات النظر قد تتمكن من محاولة:
public class HomeController: Controller{
public ActionResult ShowBasicView(string pageName){
// All URLs above map to this action
// Pass the page name to the view method to call that view.
return View(pageName);
}
}
وأنت ربما يكون أيضا لإضافة مسار لURL قاعدة، كطريق ShowBasic سوف تصل فقط لURL بقيمة السلسلة.
نصائح أخرى
ويمكنك إضافة الطريقة التالية في وحدة تحكم، فإنه
protected override void HandleUnknownAction(string actionName)
{
try{
this.View(actionName).ExecuteResult(this.ControllerContext);
}catch(Exception ex){
// log exception...
base.HandleUnknownAction(actionName);
}
}