2

I have an Object

public class Object1{
public List<Object2> {get;set;}
}


public class Object2{
public Name{get;set;}
public Address{get;set;}
}

I have a feature where the user can update just one instance of Object2. So my code for saving Object2 looks like

[HttpPost]
public ActionResult SaveObject2(Object2 obj2)
{
  if (obj2.Id == null){
       //Add Logic
       obj1.Obj2List.Add(obj2)  
    }
   else{
      // Update logic
   }
}

But obj2.Id is never null.Id is of type ObjectId. How can i check for logic to see if need to insert or update ? I am using asp.net MVC 3 and Mongo DB using the official C# drivers.

Thanks

user636525
  • 3,180
  • 9
  • 38
  • 51

1 Answers1

2

The ObjectId type is a struct, not a class - so it's never going to be null. Check for ObjectId.Empty, instead.

A word of caution, though: I suppose that you are storing the id of Object2 in some hidden field between requests. If that is the case, be aware that malicious user can easily change the ID by using an HTTP proxy (such as Fiddler), thus tricking you into believing that the Object2 is being updated instead of added.

Depending on context of what you are trying to do, I would suggest performing some additional checks to more reliably determine if you should insert or update your object.

Nikola Anusev
  • 6,940
  • 1
  • 30
  • 46
  • Thanks ! You are correct, i was using a Hidden field for storing the Id.How else can i achieve this functionality, if i dont use the hidden field ? – user636525 Jul 21 '12 at 18:47
  • 1
    @user636525 Try checking out this SO question: http://stackoverflow.com/questions/10497126/how-to-pass-sensitive-data-from-view-to-controller. It contains many helpful tips. – Nikola Anusev Jul 21 '12 at 18:56
  • I wonder how everybody else is passing the id in the ASP.Net MVC world ! I read Steve Sanderson's book and i got the idea of passing id as Hidden field from the book's samples. – user636525 Jul 21 '12 at 19:06
  • 1
    @user636525 You will find that many applications out there are simply passing it in hidden field, as you do. It's really not that bad - in worst case scenario, you'll end up with an object being added instead of edited. Whether you want to employ some additional checks really depends on the context and sensitivity of data in question. – Nikola Anusev Jul 21 '12 at 19:31