Shihan Khan
Shihan Khan

Reputation: 2188

Add record with some fields manually added from controller

I'm trying to make a website with asp.net mvc 4 & EF 6 where I want to add a record using .Add(model). But I've some fields where data needs to be entered only from controller manually. I need to enter those fields manually & the rest of the fields with .Add(). But I'm getting Validation error since manual fields are not getting added. Here are my codes,

Controller

[HttpPost]
public ActionResult Create(FlatManagement FlatTable)
{
    FlatInfo model = FlatTable.Flat;
    if (ModelState.IsValid)
    {
        var getUser = db.Clients.Where(a => a.username == User.Identity.Name).FirstOrDefault();
        FlatInfo AddFlat = new FlatInfo();
        AddFlat.admin_id = getUser.serial;
        AddFlat.user_id = 0;
        AddFlat.user_name = "N/A";
        AddFlat.user_phone = "N/A";
        db.FlatInfoes.Add(model);
        db.SaveChanges();
     }
     return View();
}

How can I add some fields manually while others will simply get added by using .Add() method? I don't want to add all the fields manually for just 3-4 fields since there are a lot of fields. It would be a lifesaving if someone can give me a solution. Thanks.

Upvotes: 1

Views: 85

Answers (3)

user3559349
user3559349

Reputation:

You current method creates a new instance of FlatInfo

FlatInfo AddFlat = new FlatInfo();

and sets some of its properties, but then you never do anything with it. Since your saving the instance of FlatInfo which is a property of FlatTable, its that instance you need to update.

[HttpPost]
public ActionResult Create(FlatManagement FlatTable)
{
    FlatInfo model = FlatTable.Flat; // this is the instance you need to update
    if (ModelState.IsValid)
    {
        var getUser = db.Clients.Where(a => a.username == User.Identity.Name).FirstOrDefault();
        model.admin_id = getUser.serial;
        model.user_id = 0;
        model.user_name = "N/A";
        model.user_phone = "N/A";
        db.FlatInfoes.Add(model);
        db.SaveChanges();
     }
     return View();
 }

Upvotes: 1

venerik
venerik

Reputation: 5904

You could initialize the fields in the constructor of the class:

public class FlatInfo 
{
    public FlatInfo()
    {
        user_id=0;
        user_name = "N/A";
        user_phone = "N/A";
        // and so on    
    }   
}

In the controller you only have to set AddFlat.admin_id (which should be named addFlat by the way).

Upvotes: 0

Brandon Osborne
Brandon Osborne

Reputation: 863

I'm pretty sure the problem you're encountering is because you're forgetting to SaveChanges after the add.

db.FlatInfoes.SaveChanges();

Upvotes: 0

Related Questions