0

I have a DB with below schema

    public partial class staging
        {
            public int id { get; set; }
            public System.DateTime createtime { get; set; }
            [DataType(DataType.MultilineText)]
            public string general { get; set; }
            public string articletype { get; set; }
        }

I have two views Create and Edit. In Create View I'm updating general but the article type I'm updating from the controller and saving a DB as below

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(staging staging)
        {

            staging.createtime = DateTime.Now;
            staging.articletype = "Stage";
            try
            {
                db.stagings.Add(staging);
                db.SaveChanges();                
            }
            catch (InvalidOperationException e)
            {
                ViewData["error"] = "An error has occured: " + e.Message;
                return View(staging);
            }

            return RedirectToAction("Details/" + staging.id);
        }

Now I have a edit field only for general. So when I go to Edit View page I see that articletype has proper value but when it return in to HttpPost of "Edit" the articletype get set to NULL, think it's because I don't have an editor field for the same. And now when I update the DB from Edit Controller it gets set to NULL there as well.

So how can I make this value persistable across views? I will only update in Create event in controller but then I always want that value to be persisted.

user3917144
  • 43
  • 1
  • 7
  • 2
    [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Nov 06 '15 at 11:00
  • ASP.NET MVC returns and interprets information sent over HTTP requests. The persisted data would have to be retrieved from a data source, such as a database or session variable, or posted back from a view back to a controller from the view to be persisted for you. – Luke Nov 06 '15 at 11:12
  • How do I post back the value from the view?? I view I have only editor fields like below

    Headline

    @Html.EditorFor(model => model.general) @Html.ValidationMessageFor(model => model.general)
    When I check Model.articletype that value is present in the view when when "staging" is returned to controller it gets set to NULL. And I don't know how to get the value into model => model.articletype
    – user3917144 Nov 06 '15 at 12:24
  • @user3917144, Use a view model containing only the properties you edit. In the post method, get the data model from the database based on the ID, then map your view model properties to the data model and save the data model. –  Nov 06 '15 at 12:32
  • you can add a `@Html.HiddenFor(model => model.articletype)` inside your form tag but you can also just not update that field in your Edit action – JamieD77 Nov 06 '15 at 16:15

0 Answers0