Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Solved it!</p> <p>If anyone is interested, my solution is the following. I created a class:</p> <pre><code>public class AttributeEditViewModel { public AttributeEditViewModel() { } public AttributeEditViewModel(Attribute attribute, SelectList categories) { this.attribute = attribute; this.categories = categories; } public Attribute attribute { get; set; } public SelectList categories { get; set; } } </code></pre> <p>My controller:</p> <pre><code> // GET: /Attribute/Edit/5 public ActionResult Edit(int AttributeID) { Attribute _attribute = ProfileDB.GetAttribute(AttributeID); var _viewmodel = new AttributeEditViewModel { attribute = _attribute, categories = new SelectList(ProfileDB.GetAllCategories(), "CategoryID", "CategoryName", _attribute.CategoryID) }; return View(_viewmodel); } </code></pre> <p>Part of my view:</p> <pre><code>&lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage&lt;KnowledgePortal.ViewModel.AttributeEditViewModel&gt;" %&gt; &lt;div class="editor-field"&gt; &lt;%: Html.DropDownList("Category", Model.categories, Model.attribute.CategoryID) %&gt; &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Save" /&gt; &lt;/p&gt; </code></pre> <p>And the postback:</p> <pre><code>// POST: /Attribute/Edit/5 [HttpPost] public ActionResult Edit(int AttributeID, FormCollection formcollection) { var _attribute = ProfileDB.GetAttribute(AttributeID); int _selcategory = Convert.ToInt32(formcollection["Category"]); _attribute.CategoryID = (int)_selcategory; try { ProfileDB.SaveChanges(); return RedirectToAction("Index"); } catch (Exception e) { return View(_attribute); } } </code></pre> <p>Basically my problem was due to my lack of understanding what updatemodel did. So after "_attribute.CategoryID = _selcategory" all I had to do was savechanges, but first I tried to updatemodel which kept failing.</p> <p>Hope this helps someone else!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload