Ehsan Akbar
Ehsan Akbar

Reputation: 7301

argument type lambda expression is not assignable to parameter type int error

I have a Major model like this:

public int Id { get; set; }
public string MajorName{ get; set; }
public string Password { get; set; }
public System.DateTime RegisterDate { get; set; }
public string StudentId { get; set; }
public string State { get; set; }
public int FacultyId { get; set; }
public int MajorId { get; set; }
public HttpPostedFileBase ImgFile { get; set; }

So I have a method like this in my repository for the above model:

public Major FindMajorById(int id)
{
    return _dbcontext.Majors.Find(id);
}

In my view I passed the id and I need the name of major:

<td>
    @{
        EducationRepositor.MajorRepository objmajor=new MajorRepository();
     }
     @Html.DisplayFor(objmajor.FindMajorById(modelItem => int.Parse(item.MajorId)).MajorName)
</td>
<td>
    @Html.DisplayFor(modelItem => item.Degree)
</td>

But I get error in my view in this line:

@Html.DisplayFor(objmajor.FindMajorById(modelItem => int.Parse(item.MajorId)).MajorName)

My error:

argument type lambda expression is not assignable to parameter type int

Upvotes: 1

Views: 9697

Answers (4)

decPL
decPL

Reputation: 5402

try the following instead:

@Html.DisplayFor(modelItem => objmajor.FindMajorById(int.Parse(modelItem.MajorId)).MajorName)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500055

I suspect you've basically got your lambda expression and your method call the wrong way round. You may want:

@Html.DisplayFor(modelItem => objmajor.FindMajorById(int.Parse(modelItem.MajorId)).MajorName)

In other words, you're creating a lambda expression which takes a model item, parses its MajorId property, calls FindMajorById, and then uses the MajorName property of the result. That lambda expression is used as the argument to DisplayFor.

I'm not an MVC expert (by any means) so it's not clear how much benefit the lambda expression provides, however - whether you could actually just call the method directly.

Upvotes: 5

Habib
Habib

Reputation: 223217

FindMajorByID expects a int value, and you are passing it a lambda expression with objmajor.FindMajorById(modelItem => int.Parse(item.MajorId).

I believe you need to pass it MajorId like:

objmajor.FindMajorById(int.Parse(item.MajorId))

Not really sure why you are doing a int.Parse since in your class MajorId is already declared as int. If your model is point to a different class, which has MajorId as string then use int.Parse otherwise you will get a compilation error.

Upvotes: 1

Christos
Christos

Reputation: 53958

You have to use int.Parse(item.MajorId) instead of

modelItem => int.Parse(item.MajorId).

The error message you got is pretty clear, you tried to pass a lambda expression as a parameter in a method, which takes only one parameter of type int. So inside your DisplayFor you have to use

objmajor.FindMajorById(modelItem => int.Parse(item.MajorId).

Upvotes: 1

Related Questions