jaya priya
jaya priya

Reputation: 75

Operator '>' cannot be applied to operands of type 'string' and 'int' using Asp.net Mvc

i am creating a simple crud system using asp.net mvc. when i enter the record and click add button this error displayed.

I get the error on this line: if (rec.id > 0)

(parameter)product rec

operator '>' cannot be applied to operands of type 'string' and 'int'**

Code which i tried

sales controller

 public ActionResult save(product rec)
    {
        bool status = false;
        if (ModelState.IsValid)
        {
            using (aspposEntities1 db = new aspposEntities1())
            {
                if (rec.id > 0) // this line i got the error
                {
                    var v = db.products.Where(a => a.id == rec.id).FirstOrDefault();
                    if (v != null)
                    {
                        v.proname = rec.proname;
                        v.cat_id = rec.cat_id;
                        v.brand_id = rec.brand_id;
                        v.qty = rec.qty;
                        v.price = rec.price;
                        db.Entry(v).State = EntityState.Modified;
                    }
                }
                else
                {
                    db.products.Add(rec);
                }

                db.SaveChanges();
                status = true;
            }
        }
        return new JsonResult { Data = new { status = status } };
    }

product class product.cs

public partial class product
{
    public string id { get; set; }
    public string proname { get; set; }
    public Nullable<int> cat_id { get; set; }
    public Nullable<int> brand_id { get; set; }
    public Nullable<int> qty { get; set; }
    public Nullable<int> price { get; set; }
}

Upvotes: 1

Views: 3651

Answers (3)

Tanveer Badar
Tanveer Badar

Reputation: 5524

Since you are unable to change the id property to be an int, here's one way to check for valid IDs.

if(int.TryParse(rec.id, out var id) && id > 0)

Upvotes: 1

Hamed Hajiloo
Hamed Hajiloo

Reputation: 1028

rec.Id Type is String.

you should convert rec.Id to int or long

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38825

The compiler is telling you exactly what the problem is. Your id property is a string, and you are comparing it to 0, an integer.

Options:

  • if(Convert.ToInt32(rec.id) > 0 (But remember null checks)
  • Change id to be an int (Preferred option)

Further reading.

Upvotes: 1

Related Questions