1

I'm new to MVC3 and have run into a little problem. I've scoured the internet and covered topics like complex model binding, etc. to no avail. If this is a simple question, I apologize in advance.

Here's what my classes look like:

public class Vod
{
    public virtual int id {get; set;}
    public virtual string myname {get; set;}
    public virtual Metadata Metadata {get; set;}
}

public class Metadata
{
    public System.Datetime? dtmCreationDate {get; set;}
    public string strCreatedBy {get; set;}
    public string strModifiedBy {get; set;}
    public System.Datetime? dtmModifiedDate {get; set;}
}

And here's a sample of my edit controller:

[HttpPost]
public ActionResult Edit(Vod vod)
{
    if (ModelState.IsValid)
    {
        db.Entry(vod).State = EntityState.Modified;
        vod.Metadata.strModifiedBy = "modified";
        vod.Metadata.dtmLastModified = DateTime.Now;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(vod);
}

My problem is trying to figure out how to set these default values in my controller whenver I create or edit a record and save the values in my database. Right now the code above does not work because I'm not doing it correctly (Object reference not set to an instance of an object.)

1 Answer 1

1

I can't tell exactly why it's not binding without seeing your view. That said, don't bind your domain model (vod) to your action. Use a view model that contains the properties of vod you need.

public class VodViewModel
{
    public int id { get; set; }
    public string myname { get; set; }
    //any properties of Metadata you need.
}

public ActionResult Edit(VodViewModel model)

Now you can fetch the vod with the corresponding id from your database (and create a new instance with the correct defaults if it doesn't exist). Then modify your vod, based on the properties in your view model, then save vod.

Sign up to request clarification or add additional context in comments.

1 Comment

I found what I was looking for here. link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.