Category Archives: Razor

Razor

[RESOLVED]Html.Helpers or Html tags ?

When we are developing our views, we can set codes as HTML.Helpers or write them as HTML tags.
However what’s best ?

EXAMPLE: CREATING A HYPERLINK

1. @Html.ActionLink("About this Website", "About")

2. <a href="/Home/About">About this Website</a>

a) So what should I use ? Should I write the HTML tags directly without razor or use helpers ?
b) If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

You can choose either. I personally use both, depending to where I’m linking.

For members and registered users, on an ASP.net project, I usually use the helpers, and on any pages accessible to unauthenticated users I use the <a href=""></a> tags.

If you use the Html.ActionLink helper, the url will always be constructed properly regardless of changes in the hosting environment, or changes between development, testing and production environments. This might not be an issue to you in which case feel
free to hard code your links. 

I have full control over my hosting environment and make sure that the development environment mirrors it as much as possible. Despite that, I use the helpers just in case. 

aganeto

If I use helperss would it cause an extra processing once I have to convert Razor to HTML ?

Yes, but it is so insignificant that if you have to worry about it, you have much bigger problems.

[RESOLVED]Unable to get updated cookie value in jquery after ajax call

I have made a simple cart example in mvc. what I’m doing is , after clicking on Add to cart span , I’m calling a Controller Action method.

And then updating the cookie value with Total no of item in cart. but it give me initial value of cookie.

This is my Ajax Code to call Controller Action

$(document).delegate('.addCart','click', function () {
            var getId = parseInt($(this).attr('id').slice(3));
            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '/Comments/CartDetailsSetGet',
                data: { Id: getId },
                success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;
                        $('.cartNum').html(getCookies);
                    }
                },
                error: function (data) {
                    alert("Error In Adding Item To Cart");
                }
            });
        });

There is span > with class cartNum in which I’m showing Total no of item in cart .

addCart is span on which I’m Clicking to Add Item In Cart.

This is my Action Method , which is My default Action

GuestbookContext db = new GuestbookContext(); // my DbContxt Class
        HttpCookie ck = new HttpCookie("CartCookie");
        public ActionResult Index()
        {
            if (Request.Cookies["CartCookie"] == null)
            {
                ck.Value = "0";
                Response.SetCookie(ck);
            }
            IList<Comment> commentList = db.Comments.ToList();
            return View(commentList);
        }

This Action Which is getting called On Ajax Request.

static List<int?> CartItemsId = new List<int?>();
        public string CartDetailsSetGet(int? Id)
        {
              if (CartItemsId.Contains(Id) != true)
                {
                    CartItemsId.Add(Id);
                    int getCount = CartItemsId.Count();
                    System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value = getCount.ToString();
                    ck.Expires = DateTime.Now.AddDays(-1);
                    var d = "";
                    if (System.Web.HttpContext.Current.Request.Cookies["CartCookie"] != null)
                    {
                        d = System.Web.HttpContext.Current.Request.Cookies["CartCookie"].Value;
                    }
                    return d.ToString();
                }
                else
                {
                    return "This Item Is Already In Cart";
                }
            
        }

Here in d I’m getting updated cookie value but in Ajax Success , this line giving me Initial value, i.e 0.

var getCookies=  @HttpContext.Current.Request.Cookies["CartCookie"].Value;

Your razor code is server-side code, it isn’t running inside the browser.  View the source of your page and you’ll see

success: function (data) {
                    var count = parseInt(data);
                    if (isNaN(count)){
                        alert(data);
                    }else{
                        var getCookies=  0;
                        $('.cartNum').html(getCookies);
                    }
                },

so no matter what happens, getCookies is always going to be 0.  You need to read the data from the document.cookie object

http://www.w3schools.com/js/js_cookies.asp

or return the data as part of your ajax method (either as well as, or instead of the cookie)

return View(new {Comments: commentList, Quantity: ck.Value);

then amend your success code to reflect this change

[RESOLVED]Post Backs Using View Models

This problem has been driving me crazy for past few weeks I wonder if anyone has some advice for me.

I have a view model, that contains 5 drop down lists.  When I create the initial view and send it out,  all 5 select lists have values from the viewmodel.  The user can see and select any value in any of them.  However, when I post back only 1 of the select
lists contain any values!

The problem this presents of course, is this, in the post back ActionMethod I first check ModelState.IsValid if it’s not valid I simply return the posted Viewmodel, but guess what those selectlists that had no values on the post now show nothing along with
the errors telling them to select something.

Ever seen this symptom before?

The issue is likely to be around the names the select elements are getting, as to be considered a list of values they need the right indexes in their names, andor your parameter for the POST action.  Post the relevant sections of the view where the lists
are created and the actions too.

One other bit of information…

I have an extension method returning this type  

public static List<SelectListItem>

The view model stages the content like this:

 public List<SelectListItem> EndHourSelectList { get; set; }

In the Validation implementation on the post back  (Locals) I see this:

+EndHourSelectList Count = 0×00000000 System.Collections.Generic.List<System.Web.Mvc.SelectListItem>

Notice the count is zero!  This implies that MVC some how created a new instance doesn’t it?  But if so why did the other one have values?

 

//This one returns values   
@Html.DropDownListFor(p => p.TT.area_worked_in, Model.AreaSelectList)

//these like this do not
@Html.DropDownListFor(p => p.StartHourSelectList, Model.StartHourSelectList);

p is the ViewModel  and TT is a type within the ViewModel

Here’s a Viewmodel example for one of the four that do not post back values in the selectlist

public List<SelectListItem> StartHourSelectList { get; set; }

Finally I build the list like this:

        public static List<SelectListItem> SetTimeTrackMinutes(this List<SelectListItem> SelectList)
        {
            if (SelectList == null) throw new InvalidOperationException("STTM300-Must Initialize the list before calling this method");
            SelectList.Add(new SelectListItem { Selected = true, Text = "Select Minutes (15 min incr.)", Value = SelectListValues.NotSelected.ToString() });
            SelectList.Add(new SelectListItem { Selected = false, Value = "0", Text = "00 (Minutes)" });
            SelectList.Add(new SelectListItem { Selected = false, Value = "15", Text = "15 (Minutes)" });
            SelectList.Add(new SelectListItem { Selected = false, Value = "30", Text = "30 (Minutes)" });
            SelectList.Add(new SelectListItem { Selected = false, Value = "45", Text = "45 (Minutes)" });
            return SelectList;
        }

I think you’re telling me I need a POCO class to model the minutes in order for the minutes to have Names?

You need a property on the view model that holds the current item

public class ViewModel
{
    public string SelectedHour { get; set; }
    public List<SelectListItem> StartHourSelectList { get; set; }
}

Controller

public ActionResult Index()
{
    ViewModel model = new ViewModel();

    SetupModel(model);

    return View(model);
}

[HttpPost]
public ActionResult Index(ViewModel model)
{
    SetupModel(model);

    return View(model);
}

private void SetupModel(ViewModel model)
{
    model.StartHourSelectList = new List<SelectListItem>();
    model.StartHourSelectList.SetTimeTrackMinutes();
}

View

@using(Html.BeginForm())
{
    @Html.DropDownListFor(p => p.SelectedHour, Model.StartHourSelectList);
    <p>
        <input type="submit" value="submit"/>
    </p>
}

Thanks Aidy;

I’ll give it a try and post back results.

Aidy;

 One question, my current post looks like this:

  @using (@Html.BeginForm("TimeTrackingForm", "ControllerName", FormMethod.Post))

Representing the TimeTrackingFrom action method in the controller that takes a Viewmodel as input parm like this:

public ViewResult TimeTrackingForm(VMTimeTrackForm TTF)

The view is strongly typed to the VMTimeTrackFrom type, so shouldn’t this be all I need on the @Html.BeginForm?

Ok Aidy very good you helped me solve this infuriating problem… I think I have a better understanding of the secretive Razor binding engine now. 

Here’s the general set of rules I’ll be following from now on.

  1. Any view model that uses an IEnumberable<ofSomething> and a DropDownListFor (or other HTML.Helper method) must specify in the first parameter where to place the selected value like this ->  DropDownListFor(p=>StuffTheSelectedValue, TheSelectList), where
    p is the Viewmodel.  The variable "StuffTheSelectedValue" in my case was a string with public Getter, Setters. [I didn't have it at first]
  2. If you don’t get that first parm right, MVC will return NOTHING for the SelectItemList itself even if it wen’t out the first time ok.  It will not signal an error anywhere in the compile, or the post back, rather it will just show up with nothing.  This
    is most likely done by the binder part of Razor whereby prior to seeing the post back in the controller, it initializes a new instance of the object, parses the querystrings and plugs the values by name where they belong.  If it can’t find anything to plug
    it leaves it blank.
  3. If you have implemented IValidatableObject the view state will most likely be invalid if the first parm was wrong, provided you are checking for something relevant or the model has proper data annotations.
  4. If the controller checks the view state and simply returns the view when the state is invalid, it will NO LONGER have any items to select!  The user will see the error messages but will not be able to do anything for them.
  5. You do not have to re-initialize the view content, if and only if, you get the first parameter correct in the DropDownListFor correct. (Or any other HTML "helper" method)
  6. If you just return the invalid view from the POST back and
    everything is correct (meaning the binder found everything to fill in)
    ,  all of the content is still there.

I too, after debugging this for a long time, had created my own post back initializes, but will not do that any more as it is a sign that something else isn’t right.  At a minimum, to me anyway, there should be some type of warning at compile time that this
could happen.  

Symptoms of this problem are :

  1.  PostBacks loose data and require re-initialization of the ViewModel.
  2. Users see data annotation or other ValidationResult errors but have no way to fix them.
  3. You find when breaking into the PostBack (very first line in the Action Method) in the controller that the viewmodel is missing data.
  4. You are writing re-initialization routines just for Post Backs.

Solution:

  1. The query strings that are returned are name/value pairs, if there is no name of MVC on the server side it will not do anything which is correct behavior.
  2. If you are using strongly typed views your BeginForm only needs to specify the controller post back action method that takes that strong type as it’s first parm.
  3. This then is the MVC method for maintaining ViewState without using ViewState.

My final solution was this in the view:

  @Html.DropDownListFor(p => p.SelectedStartHour, Model.StartHourSelectList);

This in the View Model:

public List<SelectListItem> StartHourSelectList { get; set; }
public string SelectedStartHour { get; set; }

Notice the first parm on the DropDownListFor pointed to a string value in the ViewModel, simple and it relieved me of a lot of pain in trying to understand this MVC thing.

One last thing Aidy, 

I got rid of all my re-initialization logic in the Post back…  it’s wasn’t needed any longer.  And Thanks a bunch for your help.

[RESOLVED]Render Dynamic Forms model in Razor View

Hi,

 

Im using Dynamic Forms in ASP.NET MVC sample project from this link https://mvcdynamicforms.codeplex.com/  to be used in my MVC 5 project.

 

Waht i need is to call the dynamically generated Form model to be rendered in razor view as it is currently rendered in asp.net mvc ViewPage.

here’s the current Model,Controller and how the view has called the Form object. How can i call the form object in mvc 5 razor view.

 

FormProvider Model

=================================

    public static class FormProvider

    {

        public static Form GetForm()

        {

        }

    }

 

 

HomeController

===========================

    public ActionResult Demo1()

        {

          

             var form = FormProvider.GetForm();

             

              form.Serialize = true;

             return View("Demo", form);

     }

 

 

 

ASP.NET MVC View

==================

 

     <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcDynamicForms.Form>" %>

 

     <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

 

 

      <%Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }); %>

   

 

      <%=Model.RenderHtml(true) %>

   

          <input type="submit" value="Submit" />

           <%Html.EndForm(); %>

 

        </asp:Content>

@model MvcDynamicForms.Form
@{
    // set layout if required etc
}
@using(Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })){ 
    @Model.RenderHtml(true)  
    <input type="submit" value="Submit" />
}

Thanks Mike. it worked…!

@Model.RenderHtml(true)  didn't render the html, instead it displays the string as is, but when it is wrapped in HTML.Raw(Model.RenderHtml) 
it did work.


[RESOLVED]How to get started with ASP.NET MVC ?

I’ve learned ASP.NET 2-3 years ago and I’d made some projects on ASP.NET. Now It feels like I can improve them little bit. As I’ve some 15 days free, So I was thinking to learn something new and use it in my old projects.

Actually there are some areas in my projects where I’ve to design new tools which is not possible with ASP.NET alone. For example I’m having "Virtual Classroom Project" and there is a tool called "White Board" which allow Professor to explain the things
to students. I was going to start learning Silverlight then some of my friends suggested me of ASP.NET MVC.  I’m new to ASP.NET MVC and don’t know anything about it.

How it is different from ASP.NET ?
What features does it offers ?
Whats the future of it ?
How much ASP.NET MVC coding is different from ASP.NET ?
How much time will it take to learn ASP.NET MVC ?

I’d suggest to spend 1 hour of 15 days to google all 5 questions.

Spend an hour or two and walk through this beginner’s tutorial:

http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-1

this tutorial covers most of the basics for MVC.  Please note that this tutorial is slightly dated — I believe it’s more for MVC 3 than 5, however the same principles still apply.

MVC Resources

The Getting Started MVC area on this site is a great place to start as well if you want to start learning MVC outside of a book environment. It will cover just about everything that you would need to build complete applications
and it is written by experts that apply best practices to help you build good habits for future applications.

One of the most well regarded and complete MVC-based tutorials would be the ASP.NET MVC Music Store tutorial, which you can find under the MVC section of this site. However, any
of the tutorials on this site
 should be great stepping stones to get you building your own complete MVC applications in no time.

You can find a few other resources listing off countless other MVC-based tutorials below: 

or the following more architecturally based examples :

I would definately recommend the MVC Music Store Tutorial as well as the other ones available on this site (ASP.NET) and if you are still looking for more information after that, check out some of the other links I provided. If you are still looking
for some additional tutorials or other MVC based projects, you might want to dig around on open-source sites like github and Codeplex and search for a bit more complex sites and projects.

Regarding Your Questions

22990atinesh

How it is different from ASP.NET ?

Technically, ASP.NET is still based on the same framework as Web Forms (which I am assuming that you are referring to in this context). MVC just provides a different pattern and approach to developing your applications. It is patterned after the
web and thus is stateless (so you don’t have a ViewState or any Controls). Due to it’s nature, it lends itself well to separating your concerns (all of your Presentation-related code is within the Views, your business logic will be within your
models and your Controllers will handle your data access
).

22990atinesh

What features does it offers ?

It doesn’t necessarily "offer" any newer features. Some might argue that it can be tested more easily than Web Forms (if you actually are one of the people out there writing tests consistently). I personally find it to be much simpler than Web Forms in a
very "bare-bones" sense.

22990atinesh

Whats the future of it ?

Bright. MVC has really taken off since it’s release and is continuing to gain more and more steam for developing Microsoft Web Applications. Web Forms is still completely relevant and will continue to play a major role, but MVC is certainly catching up.

It’s worth learning.

22990atinesh

How much ASP.NET MVC coding is different from ASP.NET ?

As I mentioned earlier, there are quite a few learning curves associated with it. The lack of "Controls" can be tough for those migrating from Web Forms as can the lack of a state. Since controls don’t exist, it requires developers to be much more comfortable
with using pure HTML and Javascript to accomplish many of the things that their controls did previously. 

22990atinesh

How much time will it take to learn ASP.NET MVC ?

This is something that depends entirely on you and how quickly you can understand the different components of an MVC application and how they work together. The tutorials mentioned earlier should help with this.

22990atinesh

there is a tool called "White Board" which allow Professor to explain the things to students

SignalR is a good fit for your whiteboard application. Please take look at these posts

Online
Whiteboard using HTML5 and
SignalR

A SignalR Whiteboard

22990atinesh

As I’ve some 15 days free, So I was thinking to learn something new and use it in my old projects.

I recommend learning AngularJS. It is getting more traction now-a-days. You can use MVC/WebAPI with AngularJS

Rion Williams

MVC Resources

The Getting Started MVC area on this site is a great place to start as well if you want to start learning MVC outside of a book environment. It will cover just about everything that you would need to build complete applications
and it is written by experts that apply best practices to help you build good habits for future applications.

One of the most well regarded and complete MVC-based tutorials would be the ASP.NET MVC Music Store tutorial, which you can find under the MVC section of this site. However, any
of the tutorials on this site
 should be great stepping stones to get you building your own complete MVC applications in no time.

This is something that depends entirely on you and how quickly you can understand the different components of an MVC application and how they work together. The tutorials mentioned earlier should help with this.

Thanx for help Now I can start learning ASP.NET MVC.

How is ASP.NET Web Pages, Is it better than ASP.NET MVC. Is it possible create tools that I asked for with ASP.NET Web pages. 

ASP.NET Web pages are completely different than MVC.If you are strong with HTML concepts you may be able to learn it quickly.

22990atinesh

How is ASP.NET Web Pages, Is it better than ASP.NET MVC. Is it possible create tools that I asked for with ASP.NET Web pages. 

Neither are necessarily better than the others, they are different patterns / technologies that both can be used to create Web Applications. Web Pages can be thought of as a more entry-level technology (not to say that it cannot be used to build complex
Web Applications
) whereas MVC encompasses a much larger set of libraries and in general more complex (which might be overkill for something as simple as a Web Site).

Both can create Web Applications, which is ultimately what your goal is, so either might be worth exploring as an option.

Rion Williams

22990atinesh

How is ASP.NET Web Pages, Is it better than ASP.NET MVC. Is it possible create tools that I asked for with ASP.NET Web pages. 

Neither are necessarily better than the others, they are different patterns / technologies that both can be used to create Web Applications. Web Pages can be thought of as a more entry-level technology (not to say that it cannot be used to build complex
Web Applications
) whereas MVC encompasses a much larger set of libraries and in general more complex (which might be overkill for something as simple as a Web Site).

Both can create Web Applications, which is ultimately what your goal is, so either might be worth exploring as an option.

I’ve tried ASP.NET MVC, It’s a totally new concept. I’ll learn it in the future. For now I just want to create a "White Board tool" which should be capable of displaying PPT, PDF, have Simple Drawing tool and a chat box. Can I do it with the help of HTML
5 + Jquery + CSS

22990atinesh

I’ve tried ASP.NET MVC, It’s a totally new concept. I’ll learn it in the future. For now I just want to create a "White Board tool" which should be capable of displaying PPT, PDF, have Simple Drawing tool and a chat box. Can I do it with the help of HTML 5
+ Jquery + CSS

You’ll likely need to use some kind of server-side code in order to properly retrieve your various types of files (unless they are explicitly stored in the same directory as your project and you would be accessing them through links). Additionally,
most browsers are not going to be able to "display" files like PowerPoint natively, you’ll need to look into a library as a way to present these within the browser (although there are other
ways to embed a PowerPoint presentation within your web application
).

Finally, a drawing tool shouldn’t be too out of reach as it’s very commonly implemented using the HTML <canvas> element along with a bit of Javascript / jQuery. If you search around for it, you shouldn’t have too much trouble finding a simple HTML5 Drawing
implementation. There are quite a few "it depends" answers related to a project like this and I am sure that you should be able to accomplish something like it using either a pure HTML5 / Javascript implementation or one that leverages ASP.NET (either
Web Pages or MVC
).

zing!

22990atinesh

Can I do it with the help of HTML 5 + Jquery + CSS

Have you looked at my earlier links?

Online
Whiteboard using HTML5 and
SignalR

A SignalR Whiteboard

Let’s see videos to understand about MVC .NET. You can understand some things

http://youtu.be/lG49gPy-hG0

http://youtu.be/ZKYlK4RFa1I

http://youtu.be/-ZdgU8Hngxw

Hi,

Please use below link to know about basic MVC history, basic, business section are same what we had been used in ASP.Net. 

http://www.asp.net/mvc

http://mvc4beginner.com/Tutorial/

http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3razor.aspx

http://20fingers2brains.blogspot.com/2014/01/introduction-to-aspnet-mvc-3.html

http://www.microsoftvirtualacademy.com/training-courses/introduction-to-asp-net-mvc

Please don’t rush to learn short time, please work out what you learn day by day.

Thanks,

Jai.

Rion Williams

22990atinesh

I’ve tried ASP.NET MVC, It’s a totally new concept. I’ll learn it in the future. For now I just want to create a "White Board tool" which should be capable of displaying PPT, PDF, have Simple Drawing tool and a chat box. Can I do it with the help of HTML 5
+ Jquery + CSS

You’ll likely need to use some kind of server-side code in order to properly retrieve your various types of files (unless they are explicitly stored in the same directory as your project and you would be accessing them through links). Additionally,
most browsers are not going to be able to "display" files like PowerPoint natively, you’ll need to look into a library as a way to present these within the browser (although there are other
ways to embed a PowerPoint presentation within your web application
).

Finally, a drawing tool shouldn’t be too out of reach as it’s very commonly implemented using the HTML <canvas> element along with a bit of Javascript / jQuery. If you search around for it, you shouldn’t have too much trouble finding a simple HTML5 Drawing
implementation. There are quite a few "it depends" answers related to a project like this and I am sure that you should be able to accomplish something like it using either a pure HTML5 / Javascript implementation or one that leverages ASP.NET (either
Web Pages or MVC
).

Hello Rion William,
I’ve read SignalR articles from official ASP.NET website. Its a very cool and easy concept. A simple "Chat box" App requires only few lines of code (hardly 7-8 lines of code after adding the SignalR library) and its quite self explanatory. And Ya HTML 5 canavas
is also easy way to create white board. I can combine these two to make a simple White board tool, But I’m trying to build a more advanced white board tool with more flexibility and more featues. Please see this post

http://forums.asp.net/t/2012233.aspx?What+you+can+and+can+not+do+with+ASP+NET+SignalR+

Pro ASP.NET MVC 5

[RESOLVED]watermark image dynamically while uploading before saving it

how to watermark image before saving it

using webImage i have to save the image first and give path of it

is it possible to watermark first and save

I googled "asp.net add watermark to uploaded image" and this was the first result, you can find others too

http://dotnetawesome.blogspot.co.uk/2013/12/how-to-add-watermark-text-to-image.html

AidyF : thanks for your reply

but i want this in mvc

It doesn’t make a difference, the watermark code is the same.  If it is the image upload you don’t know how to do then you should be more explicit, but even then just google "image upload mvc" and you’ll find lots of examples.  Once you have a handle on
the image as a stream you can watermark and save it as per the link above.  Or just google "mvc add watermark to uploaded image" and you’ll probably find an mvc example.  Some things are easily researched yourself, the code is all out there.

http://www.aurigma.com/upload-suite/developers/aspnet-mvc/how-to-upload-files-in-aspnet-mvc

http://blog.tallan.com/2011/02/04/watermarking-images-using-the-razor-webimage-helper/

[RESOLVED]Query result that doesn’t make sense (to me)

Hallo , I’m trying  to get  a results base on day of the week  

By doing as follow .

 public PartialViewResult _course()
        {
            int myweekday = 1;

            DateTime dt = DateTime.Now;
            if (dt.DayOfWeek == DayOfWeek.Sunday) myweekday = 1;
            else if (dt.DayOfWeek == DayOfWeek.Monday) myweekday = 2;
            else if (dt.DayOfWeek == DayOfWeek.Tuesday) myweekday = 3;
            else if (dt.DayOfWeek == DayOfWeek.Wednesday) myweekday = 4;
            else if (dt.DayOfWeek == DayOfWeek.Thursday) myweekday = 5;
            else if (dt.DayOfWeek == DayOfWeek.Friday) myweekday = 6;
            else if (dt.DayOfWeek == DayOfWeek.Saturday) myweekday = 7;

            ///for Today
            var _sh = (from c in db.course select c).OrderBy(d => d.daynumber)
                .ThenBy(t => t.Time).Where(w => w.daynumber == myweekday);
            ///for the Next day 
            ///the result here should be 2 (today is sinday and sunday=1)
            ///
            ViewBag.next = (from c in db.course select c).Where(w => w.daynumber == (myweekday + 1))
                            .OrderBy(d => d.daynumber).ThenBy(t => t.Time);

My razor :

 @*the view bag should be null i have only results for sunday and thiis should point to manday*@
                @if (ViewBag.next != null)
                {
                    <h3>tomorrow</h3>
                    foreach (var item in ViewBag.next)
                    {
                        <h3>@ViewBag.Tomorrow</h3>


                        @item.daynumber
                        @item.Writer.Name
                    }
                }

how ever I’m getting the <h3>tomorrow</h3> display  any idea where is my mistake ?

The issue is that your ViewBag may not be null, but may simple exist with 0 items in it. You might want to change the code in your View to check if it is not null and not empty :

@if (ViewBag.next != null && ViewBag.next.Any())
{
       <!-- Omitted for brevity -->
}

You might be able to dramatically simplify your code as you can convert your DayOfWeek value into an integer using the Convert.ToInt32() method as seen below :

public PartialViewResult _course()
{
        // Get the current DateTime
        DateTime dt = DateTime.Now;

        // Since the Day of Week is 0-based, you'll need to increment it by 1
        int myweekday = Convert.ToInt32(dt.DayOfWeek) + 1;


        ///for Today
        var _sh = db.course.Where(w => w.daynumber == myweekday)
                           .OrderBy(d => d.daynumber)
                           .ThenBy(t => t.Time);

        ///the result here should be 2 (today is sinday and sunday=1)
        ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                                .OrderBy(d => d.daynumber)
                                .ThenBy(t => t.Time);
}

thanks a lot Mr. Rion,

i’m getting this Error by using Any

‘System.Data.Entity.Infrastructure.DbQuery<MyProjectName.Models.MyClassName>’ does not contain a definition for ‘Any’

 @if (ViewBag.next != null && ViewBag.next.Any())

Try including a ToList() to actually store a collection of your values in memory instead of a DbQuery :

///the result here should be 2 (today is sinday and sunday=1)
ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                        .OrderBy(d => d.daynumber)
                        .ThenBy(t => t.Time)
                        .ToList();

Rion Williams

Try including a ToList() to actually store a collection of your values in memory instead of a DbQuery :

///the result here should be 2 (today is sinday and sunday=1)
ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                        .OrderBy(d => d.daynumber)
                        .ThenBy(t => t.Time)
                        .ToList();

thanks Rion ,

but no, it’s not null .

john_mm

but no, it’s not null .

Right.

The ToList() call will result in an actual collection of results (in memory) and allow you to use the Any() extension method to check if the collection actually has any elements. You still need the appropriate null check to avoid any null-reference exceptions
when calling the Any() call.

<!-- This ensures that your next collection isn't null and actually contains at least one element -->
@if (ViewBag.next != null && ViewBag.next.Any())
{
     <h3>tomorrow</h3>
     <!-- This will iterate through each value within your collection (which is guaranteed to not be empty) -->
     @foreach (var item in ViewBag.next)
     {
            <h3>@ViewBag.Tomorrow</h3>
            @item.daynumber
            @item.Writer.Name
     }
}
 ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                          .OrderBy(d => d.daynumber)
                          .ThenBy(t => t.Time)
                          .ToList();

     @if (ViewBag.next != null && ViewBag.next.Any())
                {
                    <h3>bla</h3>

                    foreach (var item in ViewBag.next)
                    {


                    }

                }

[RuntimeBinderException: 'System.Collections.Generic.List<Hagadol12_8.Models.Course>' does not contain a definition for 'Any']
   CallSite.Target(Closure , CallSite , Object ) +137

john_mm

var stuff = db.course.Where(w => w.daynumber == (myweekday + 1))
                          .OrderBy(d => d.daynumber)
                          .ThenBy(t => t.Time)
                          .ToList();
 

 Validate stuff has stuff in it before working on ViewBag.  Because the viewbag is a dynamic object you’re playing hide and seek with what’s in the View bag.

Separate your concerns by putting all db results into stuff then work on stuffing the Viewbag.  Or better yet don’t even use the viewbag, use strongly typed views.

 

Hi,

john_mm

does not contain a definition for ‘Any’]

If not possible with Any() try with Count

@if (ViewBag.next != null && ViewBag.next.Count > 0)

john_mm

[RuntimeBinderException: 'System.Collections.Generic.List<Hagadol12_8.Models.Course>' does not contain a definition for 'Any']
   CallSite.Target(Closure , CallSite , Object ) +137

The Any() extension method should be available on any IEnumerable collections as long as you are using LINQ either explicitly in your View :

using System.Linq;

or by defining it within the web.config (to be available within your Views) :

<pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Linq" />
      </namespaces>
</pages>

If you are still continuing to encounter issues, you might consider using two of the following options :

  • Consider using the Count() method instead to see if that allows you to perform your check (to see how many values are available in your collection) :
    @if (ViewBag.next != null && ViewBag.next.Count() > 0)
    {
    
    }
  • Or an even easier approach would be to not use the ViewBag at all and actually pass in a strongly typed collection of your values to your View, which would allow you to access them via the Model using :
    // Build your collection of courses
    var courses = db.course.Where(w => w.daynumber == (myweekday + 1))
                           .OrderBy(d => d.daynumber)
                           .ThenBy(t => t.Time)
                           .ToList();
    
    // Pass your courses to your View
    return View("_YourViewName",courses);

    Doing this would allow you to access your courses using a strongly-typed collection instead of a dynamic ViewBag variable as seen below :

    <!-- Define your Model as a List of Course objects -->
    @model List<Hagadol12_8.Models.Course>
    
    <!-- Add your Logic -->
    @if (Model != null && Model.Any())
    {
    
        <!-- Loop through the strongly-typed Course objects in your Model -->
        @foreach (Hagadol12_8.Models.Course course in Model)
        {
    
        }
    }

you are using viewbag as a list data so have to check if there is any element in that list

[RESOLVED]Thoughts on Angular

I was reading up on Angular for the first time the other day and thought to myself "Unbelievable….here’s a framework that could care less about Separation of Concerns" which of course is diametric to what MVC is all about.  Any thoughts on that?  It was
just my first impression… What do you like about Angular?  And why should I consider using it?

Angular has some features which you can use, but there are other ways to achieve what you can get in angular js. If you follow angular it will be always the same format sending the JSON object from mvc controllers. asking the browser to use angular to format
json objects into required UI. It has advantages like low network consumption as json alone is sent to client, quicker response time as razor engine is hardly used you are not building the whole html at server, only the layout will be generated from mvc and
rest of the dropdowns radio buttons are generated by angular js. One thing you might have to consider is if you use any other Jquery controls like the scroller, popup, dropdowns are they compatible with angular js.

v2kea60

"Unbelievable….here’s a framework that could care less about Separation of Concerns"

AngularJS framework is built using MV* pattern (more popularly MVVM) which clearly have "separation of concerns". Similar to MVC, MVVM and Angular has Separation of concerns built in. Unfortunately most of the examples in Angular are primitive and hence
you may get the feeling like this. JavaScript as a whole suffers this separation of concerns feeling. I believe the reason is most of the current adopters of Angular and Javascript is frontend developers. But this is changing rapidly. Please take a look at
my blogs on this

Where is Model in AngularJS

Revealing Module pattern in AngularJS

Visual Studio Project Structure for Angular

Also take a look at my demo project at GitHub

https://github.com/prasannapattam/ng-demos/tree/master/ng-demos/ng-styleguide

v2kea60

What do you like about Angular?

A great framework to build single page applications. It drastically reduces your code. I also feel that Angular is going to de facto standard for Single Page Application

v2kea60

why should I consider using it?

If you are building a single page application, then I strongly recommend Angular. Otherwise look at Knockout

[RESOLVED]The extension '.cshtml' doesn't work on subdirectory

cshtml pages don’t work only in a sub-directory of a subdomain. We have a main domain where cshtml works on ‘X’ subdirectory folder, but we have a sub-domain where the root directory is a sub-directory of the main domain and cshtml doesn’t work there. On
IIS, main domain and sub-domain have their own application pool. The ‘X’ sub directory of the main domain has been converted to application and cshtml pages are working. We tried to accomplish the same process, but we have the following error :

This type of page is not served. Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension ‘.cshtml’ may be incorrect. Please review the URL below and make sure that it is spelled correctly.

Requested URL: /test/test.cshtml

This a simple test file, which works on the main domain sub-directory, but not on the sub-domain sub-directory. I think it is the parent domain that blocks, "it has been explicitly forbidden."

On Handler Mappings the extension is active. (Windows Server 2012 R2, IIS 8.5)

The server has the .NET Framework 4 installed. Also the application is running in an application pool that’s configured to use that version of the.NET Framework.

/home/main_domain/X_subdirectory (works cshtml)

/home/main_domain/sub_domain/subdirectory (doesn’t work cshtml)

Do you have any ideas ?

The following code gives to me an Internal error :

<system.webServer>
   <security>
    <requestFiltering>
       <fileExtensions>
          <remove fileExtension=".cshtml" />
          <add fileExtension=".cshtml" allowed="true" />
       </fileExtensions>
     </requestFiltering>
   </security>
 </system.webServer>

Ref : http://www.asp.net/web-pages/overview/more-resources/aspnet-web-pages-%28razor%29-troubleshooting-guide

Adding this to my web.config doesn’t work neither.

<configuration>
  <appSettings>
    <add key="webpages:Enabled" value="true" />
  </appSettings>
</configuration>

The sub directory where it works is configured as a Web Application :

  1. On IIS manager (Win + R and copy %systemroot%system32inetsrviis.msc)

  2. On the directory in the tree on the left (SitesMain_domainsub_directory

  3. List item Right click on it and I chose "Convert to Application"

If you directly put cshtml in browser it will not work. You need to put your valid URL which you have configured through routing.

When I put directly the cshtml on the browser works for the other subdirectory. It is a simple .cshtml page.

Hi coronadouglass,

According to your description, it works fine if you convert it to the application. So I think it is the independent project and you let it in the main project.

If that is the case, since they are independent, you need to convert it to the application.

Best Regards

Starain Chen

[RESOLVED]datepicker work once in partialview mvc5

Hi,I’m having this annoying problemwith datepicker.
I’m working with MVC5, Bootstrap, jquery 1.10.2 and jquery-ui-1.11.1.
I have 2 datepickers in a partial view that is call it from a bs modal, and when I show the modal a second time, the datepicker stop working, and I’ve tried almost everything, take a look:

**JS Code**

<script type="text/javascript">
(function () {
$("#EDate").datepicker();
$("#RDate").datepicker({ minDate: "-1d" });

$("#divm").on("hidden.bs.modal", function () {
$(".datepicker").datepicker("destroy");
$(".datepicker").removeClass("hasDatepicker").removeAttr('id');
})
})();
</script>

**Razor Code**

@Html.EditorFor(model => model.EntryDateOperation, new { htmlAttributes = new { id = "EDate", @class = "form-control datepicker" } })
@Html.EditorFor(model => model.EntryDateOperation, new { htmlAttributes = new { id = "RDate", @class = "form-control datepicker" } })

**The bootstrap modal**

<div id="divm" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="Embarcaciones" aria-hidden="true">
<div class="modal-dialog" style="text-align:right">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div style="text-align:left">
<h4 class="modal-title" id="mTitulo">Nueva Embarcaci&oacute;n</h4>
</div>
</div>
<div id="mEdit" class="modal-body" style="width:100%; text-align:center">
@{Html.RenderPartial("_myclass", Model.Myclass);}
</div>
</div>
</div>
</div>

**and I added z-index on jquery ui css**

.ui-datepicker {
width: 17em;
padding: .2em .2em 0;
display: none;
z-index: 9999999 !important;
}

As you can see I have tried almost everything, but I don’t know what else can I do, Thanks for any kind of help :)

lebarros

$(".datepicker").datepicker("destroy");

I believe this could be the problem. You are removing the date picker with the destroy method