开发者

How do I redirect to a page with an ID that doesn't exist yet?

开发者 https://www.devze.com 2023-04-13 01:56 出处:网络
Basically put, I have an action that saves a form to a database, then redirects the user to a list. From this list, the user can select a few actions.

Basically put, I have an action that saves a form to a database, then redirects the user to a list. From this list, the user can select a few actions.

One of these actions is essential and I would like the user to be passes directly to this straight after creating an object, however, as the ID of the first object does not exist yet, I am not sure how to pass the ID through.

For example Currently -

            //Excerpt  
            db.form.Add(ViewModel);
            db.SaveCha开发者_StackOverflow中文版nges();
            return RedirectToAction("List");

Then I have a list that is pulled in the normal way, and there is a link that the user can click to go to /stage2/(id).

What I would ideally like is to change my code to something like:

            //Excerpt  
            db.form.Add(ViewModel);
            var newentry = db.SaveChanges();
            return RedirectToAction("Stage2", new {id = newentry));

I have seen that calling SaveChanges() in this manner results an int being returned, but, I have tried and it doesn't seem to pull the ID of the object, I have tried a few other things but am unsure of the syntax to use.

All I can think is to detach the object, then select it again and return, but, is there a more "slick" or direct way of doing this?



EDIT - I think I have worked this out... but, I need to wait 7 hours until I can post an answer.

Unless I am mistaken - in which case, please can someone tell me!... It looks like that Entity Framework automatically updates the object that you pass it.

When I pass it a form object, upon calling SaveChanges, it automatically sets the ID of the form object.

So, all I needed was:

        //Excerpt  
        db.form.Add(ViewModel);
        return RedirectToAction("Stage2", new {id = ViewModel.id));


Try this:

form ViewModel = new form();
// Add all your operations on the ViewModel object
db.AddToform(ViewModel);
db.SaveChanges();
//int id = ViewModel.id;
return RedirectToAction("Stage2", new {id = ViewModel.id));

After calling the "SaveChanges" method, your ViewModel id property gets updated


Unless I am mistaken - in which case, please can someone tell me!... It looks like that Entity Framework automatically updates the object that you pass it.

When I pass it a form object, upon calling SaveChanges, it automatically sets the ID of the form object.

So, all I needed was:

    //Excerpt  
    db.form.Add(ViewModel);
    return RedirectToAction("Stage2", new {id = ViewModel.id));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号