2011-11-04 56 views
1

我使用jQuery的日期選擇器小部件與asp.net mvc3。我希望用戶點擊日期並轉到該日期的網址。例如。 http://mysite.com/home/index/20111231jquery datepicker轉到相對日期url

我發現一個類似的帖子,但它不會去相對的網址。 jQuery UI Datepicker go to date URL

我的代碼適用於第一次點擊,但在第二次點擊後,網址變成了雙倍並給了我404錯誤。 第1點擊:http://mysite.com/home/index/20111231 第2點擊:http://mysite.com/home/index/home/index/20111231

代碼鑑於:

public class HomeController : Controller 
{ 
    public ActionResult About() 
    { 
     return View(); 
    } 

    public ActionResult Index(string id) 
    { 
     ViewBag.Message = "Welcome " + id; 

     return View(); 
    } 
} 

修訂:在控制器

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#datepicker").datepicker({ 
      beforeShowDay: function (date) { 
       return [true, "active"]; 
      }, 
      onSelect: function (dateText, inst) { 
       document.location.href = "Home/Index/" + dateText; 
      }, 
      onChangeMonthYear: function(year, month, inst) 
      { 
      }, 
      dateFormat: "yymd", 
      showOtherMonths: true, 
      selectOtherMonths: true, 
      changeMonth: true 
     }); 
    }); 
</script> 
<h2>@ViewBag.Message</h2> 
<div id="datepicker"> 
</div> 

代碼 我的解決辦法是在生成的虛擬路徑服務器並將其粘貼到客戶端html。

document.location.href = '@Request.Url.GetLeftPart(UriPartial.Authority)@HttpRuntime.AppDomainAppVirtualPath' + "/Home/Index/" + dateText; 

回答

1

你需要一個/添加到您的路徑的開頭:

document.location.href = "/home/Index/" + dateText;

+0

我試着添加「/」開始,但我需要硬編碼的虛擬目錄名稱也。這不是一個好的解決方案。但你提醒我,我可以得到服務器上的虛擬目錄,並將其粘貼在客戶端html上。查看解決方案的更新。 –

1

我建議使用URL助手構建URL。這樣它仍然工作後,你改變了路線等。

@Url.Action("Index", "Home", new { id = dateText }) 
+0

它幾乎工作,但dateText是JavaScript,而不是C#代碼。所以我得到編譯錯誤。 –

+1

啊,我可以強制Url Helper創建路由URL,然後在javascript中解析它。 var url ='@ Url.Action(「Index」,「Home」,new {id = 0})'; url = url.substr(0,url.length - 1)+ dateText; document.location.href = url; –

+0

你說得對 - 如果使用JavaScript構建它更加棘手。我認爲解析方法是一個適當的解決方法。 – Marc