how to check null or empty value in mvc view page - asp.net-mvc-2

I want to check null or empty in view page. i gave code. but it is showing the error. i don't know how to give?
my code is
<% foreach (Models.JobPreferredIndustry jpi in Model.JobPreferredIndustries)
{ %>
<% if (jpi != null) { %>
<%:jpi.Industry.Name %>
<%} %>
<%if (string.IsNullOrEmpty(jpi))
{ %>
----------------
<%} %>
<%}%>

I know this is a bit late... Is the error Object reference not set to an instance of an object? Maybe the problem is that your Model or Model.JobPreferredIndustries is null.
You can add check for null before the foreach statement:
if(Model != null)
{
...
or
if(Model.JobPreferredIndustries != null)
{
...

Related

How to conditionally display variables with EJS

This question may seem duplicate, but checking out the related questions didn't give satistfying answers.
Is there a better way of outputing (writing) variables in EJS, other then the commonly suggested
<% if (user) { %><%= user.name %><% } %>
I am searching for something like
<% if (user) {write(user.name)} %>
The closest thing I found was
<%= user.name ? user.name : '' %>
in this good post from 2015: https://blog.joeandrieu.com/2013/10/16/how-to-conditionally-display-variables-with-ejs/, but this approach fails, at least in Node 10, as I get Cannot read property 'name' of undefined. Am I doing it wrong? Or is there another way?
Check if user object is undefined. Use this:
<%= typeof user != 'undefined' ? user.name : '' %>
Alternatively you can attach your user object on locals , so you can use it this way:
<%= user.name ? user.name : '' %>

Why is my date_field parameter nested inside the label name?

in my controller, I have this:
def index
filter = []
if !params[:paid].blank?
paid = params[:paid]
filter << ["copay_received = '#{paid.to_s}'"]
end
if !params[:junk].blank?
junk = params[:junk][:effective_on]
filter << ["clients.effective_on >= '#{junk.to_s}'"]
end
#unpaids = Appointment.joins(:client).where(filter.join(" AND "))
end
which is based on the (non-accepted) answer to this question.
Here is the form I used on the index page to search it:
<%= form_tag("/", method: "get") do %>
<%= label_tag(:paid, "Search for:") %>
<%= check_box_tag(:paid) %>
<%= date_field(:junk, :effective_on) %>
<%= submit_tag("Search") %>
<% end %>
I finally got my date_field working (as shown with the effective_on parameter).
But my question is why do I have to go an extra layer down into the params hash to get :effective_on while I don't have to do the same thing to reach :paid?
you are using the wrong method. it should be date_field_tag.
the date_field method is supposed to be used with an object form like
form_for #user do |f|
f.date_field :born_on
end

Rails Tutorial 3.2 Chapter 8 error: NoMethodError in SessionsController#create

I'm going through the rails tutorial and my login page is throwing an exception after exercise 8.1.5 when I click the login button with no email or pw entered:
http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec-rendering_with_a_flash_message
Error:
NoMethodError in SessionsController#create
undefined method `[]' for nil:NilClass
app/controllers/sessions_controller.rb:7:in `create'
SessionsController matches the final code exactly for the Create method
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase) #line 7
if user && User.authenticate(params[:session][:password])
#will fill this in later
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
end
end
I did change the button label to Log in instead of "Sign in" as that is too confusing with "Sign up", but I didn't think that would create the problem. sessions\new.html.erb
<% provide(:title, "Log in") %>
<h1>Log in</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(:sesssion, url: sessions_path) do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Log in", class: "btn btn-large btn-primary" %>
<% end %>
<p>New user? <%= link_to "Sign up now!", signup_path %></p>
</div>
</div>
This post hints that I need a method in my user model, but adding that didn't help:
NoMethodError in SessionsController#create
I tried adding this to user.rb, but it didn't help
results from find_by_email executed in function differs from console:
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return user.nil? ? nil : user
end
Any ideas would be greatly appreciated!
I've looked at the example from the book and your code and I noticed this line
if user && User.authenticate(params[:session][:password])
your User.authenticate should be lowercased to user.authenticate. Revert back to your original code.
I have just had the same problem and found that in fact i needed [:sessions] with an s on the end!
So line reads
if user && User.authenticate(params[:sessions][:password])
Hope this helps someone in the future!
I had the same problem after doing exercise 1 in chapter 8 where I replaced the use of form_for with form_tag. This resulted in the name attributes in the generated input form fields changing from name="session[email]" and name="session[password]" to name="email" and name="password". Subsequently, I needed to access the params using params[:email] and params[:password] instead of params[:session][:email] and params[:session][:password].
My new Sessions controller looks like this:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email].downcase)
if user && user.authenticate(params[:password])
sign_in user
redirect_to user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
sign_out
redirect_to root_url
end
end
This solved the problem for me. Hope this is helpful to someone else.
In this section from the tutorial chapter 8, all instances of [:session] should be [:sessions]. Hope that helps.
class SessionsController < ApplicationController
.
.
.
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
.
.
.
end
Could you confirm the word 'session' in app/view/session/new.html.erb spelling correct?
I see you wrote:
form_for(:sesssion, url: sessions_path) do |f|
But in app/controllers/sessions_controller.rb, you wrote:
user = User.find_by_email(params[:session][:email].downcase) #line 7
They must be the same.

Asp.net MVC 2 CascadingDropDown

Hi, this is my Controller Code:
public ActionResult Create()
{
makelist = new SelectList(db.CountryMasters.ToList(), "CountryID", "CountryName",1);
ViewData["CounrtyMaster"] = makelist;
var modelList = new CascadingSelectList(clientMasterManagement.GetState(makelist.SelectedValue.ToString()), "StateID", "StateName");
ViewData["StateMaster"] = modelList;
return View("Create");
}
and this is my View Code:
<div class="editor-field">
<%= Html.DropDownList("CountryID", ViewData["CounrtyMaster"] as SelectList)%>
<%= Html.ValidationMessageFor(model => model.CountryID) %>
</div>
<%= Html.CascadingDropDownList("StateMaster","CountryMaster")%>
when I select upper list it's not affecting the second one, can anyone help me here???
User CascadingSelectList function instead of SelectList in your controller action
var makelist = new SelectList(db.CountryMasters.ToList(), "CountryID", "CountryName",1); ViewData["CounrtyMaster"] = makelist;
var modelList = new CascadingSelectList(clientMasterManagement.GetState(makelist.SelectedValue.ToString()), "StateID", "StateName");
ViewData["StateMaster"] = modelList;
Html.CascadingDropDownList is not a standard MVC helper. I take it that you are using Stephen Walther's helper. If so this question will help you out:
ASP.NET MVC - Cascading Drop Down

how do I generate a tag cloud in acts_as_taggable_on?

I can't debug why I am getting an error:
class VendorsController < ApplicationController
def tag_cloud
#tags = Vendor.tag_counts_on(:tags)
end
I set this class as Taggable:
class Vendor < ActiveRecord::Base
acts_as_taggable_on :tags, :competitors
I include the TagsHelper:
module VendorsHelper
include TagsHelper
end
This is in my View:
<% tag_cloud(#tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
<%= link_to tag.name, { :action => :tag, :id => tag.name }, :class => css_class %>
<% end %>
This is the error that I get:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
Each instance of Vendor has at least one Tag.
Got it, I needed to add: #tags = Vendor.tag_counts_on(:tags) in the index controller.