2010-02-19 103 views
0

我是通過在我的應用中實現本機CAPTCHA(即不是reCaptcha)解決方案的一部分。我已經按照Sanderson的書Pro ASP.NET MVC Framework的內容構建了它。它的建成爲HtmlHelper類,所以我可以把它在我看來,像ASP.NET MVC - 如何在控制器中呈現HtmlHelper方法?

<%= Html.Captcha("nameOfGeneratedCaptchaIdField")%> 

但是,要使用這個我需要一種方法來允許它再次生成。即如果您無法閱讀此內容,請單擊[此處]。

這[這裏]我想成爲一個控制器動作,生成驗證碼圖像並吐出html。 (我將在Ajax.ActionLink鏈接中使用它。)

但是我在計算如何在控制器中執行此操作時遇到了問題。如何獲得對的HtmlHelper一個手柄的需要的一個的HtmlHelper

public ActionResult RegenerateCaptcha(string name) 
{ 
    var myHtmlHelper = ???; 
    var newCaptcha = Captcha.Helpers.CaptchaHelper.Captcha(myHtmlHelper, name); 


    if (Request.IsAjaxRequest()) 
    { 
     return Content(newCaptcha.ToString()); 
    } 
    else 
    { 
     return Content(newCaptcha.ToString()); 
    } 
} 

我的驗證碼助手編碼爲:

// this is invoked in a view by <%= Html.Captcha("myCaptcha") %> 
public static string Captcha(this HtmlHelper html, string name) 
{ 
    // Pick a GUID to represent this challenge 
    string challengeGuid = Guid.NewGuid().ToString(); 
    // Generate and store a random solution text 
    var session = html.ViewContext.HttpContext.Session; 
    session[SessionKeyPrefix + challengeGuid] = MakeRandomSolution(); 

    // Render an <IMG> tag for the distorted text, 
    var urlHelper = new UrlHelper(html.ViewContext.RequestContext); 
    string url = urlHelper.Action("Render", "CaptchaImage", new{challengeGuid}); 
    // fill it with a newly rendered image url, 
    // plus a hidden field to contain the challenge GUID 
    return string.Format(ImgFormat, name, challengeGuid, url); 
} 

我想我可以只複製出來的助手,並將其粘貼到我的控制器動作,但似乎有點貧民窟...

謝謝。

+0

http://stackoverflow.com/questions/621235/using-htmlhelper-in-a-controller – womp 2010-02-19 21:45:28

回答

2

您不必在控制器中創建html助手。您應該創建局部視圖返回的驗證碼並返回PartialViewResult:

public PartialViewResult Captcha() 
{ 
    return PartialView("Captcha"); 
} 
+0

我同意。這總是最好留給PartialView,而不是在控制器方法中呈現的東西。分開演示文稿並將其留給View。 – 2010-02-19 21:50:35

+0

太棒了。奇蹟般有效!謝謝! – Scott 2010-02-19 22:12:57

0

@LukLed是正確的。 PartialView更適合這個,你也可以看看this

相關問題