简体   繁体   中英

Building HTML Calendar Using ASP.NET MVC Razor

I am trying to create a similar calendar as shown in the image below:

calendar sample image

I have the following code:

<table>

@for(var item = Model.StartDate; item <=Model.StartDate.AddDays(7); item = item.AddDays(1))
{   
    <th>@item.ToString("ddd")</th>  

    <tr>
    <td>@item.ToString("MMM") @item.ToString("dd")</td>
    </tr>
}



</table>

Which of course does not render the correct result. What can I do to produce the result shown in the image? I don't care about the in-active dates.

Your HTML should look more like this:

<table>
    <thead>
        <tr>
          @for(var item = Model.StartDate; item <=Model.StartDate.AddDays(7); item = item.AddDays(1))
          {   
                <th>
                    <b>@item.ToString("ddd")</b>  
                    <div>@item.ToString("MMM") @item.ToString("dd")</div>
                </th>
           }
        </tr>
    </thead>
    <tbody>
       <!-- Load rows -->
    </tbody>
</table>

That just gives you an un-styled table header. If all that time range data is just static (doesn't depend on what the StartDate is) as it appears in the image - you said the inactive doesn't matter - then just write it all out

This should get you closer (you have to fiddle with the html and times yourself);

The View:

<table>
    <thead>
        <tr>
            @for (int i = 0; i < Model.NumberOfDays; i++)
            {
                <th>
                    @Model.StartDate.AddDays(i).ToString("ddd")
                </th>
            }
        </tr>
    </thead>
    <tbody>
        <tr>
            @for (int i = 0; i < Model.NumberOfDays; i++)
            {            
                <td>@Model.StartDate.AddDays(i).ToString("MMM") @Model.StartDate.AddDays(i).ToString("dd")</td>
            }
        </tr>
    </tbody>
</table>

The Action in the Controller:

public ActionResult Index()    
{    
    CalendarViewModel model = new CalendarViewModel
        {
            NumberOfDays = 7,
            StartDate = DateTime.Now
        };
        return View(model);

}

The Viewmodel:

public class CalendarViewModel
{
    public int NumberOfDays { get; set; }
    public DateTime StartDate { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM