0

I'm trying to create a new object in the database which will take a value of a database entry based on the choice of a DropDownList.

In the following example I want a new "Domena" object to hold the value of property "Cena" which belongs to Class TLD, the property "Cena" has been created and it's in the database as decimal value. It should take the value of a "Cena" from TLD Class when given TLD has been selected from the DropDownList.

Here's the Domena Class model :

public class Domena
{
public int DomenaID { get; set; }
public int TLDID { get; set; } // foreign id
public int KlientID { get; set; }
// irrelevant code omitted
public decimal Cena { get; set; } // value which should be copied from "Cena" from TLD CLASS
public virtual TLD TLD { get; set; }
public virtual Klient Klient { get; set; }  

}

Here's the TLD class :

public class TLD
{
public int TLDID { get; set; }
public string Typ { get; set; }
public decimal Cena { get; set; }
public virtual ICollection<Domena> Domeny { get; set; }
}

I've been looking at : http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx but I couldn't find a solution for my self. What ive tried already is this code in my HTTP GET Create action:

    public ActionResult Create(TLD cena)
    {
        ViewBag.TLDID = new SelectList(db.TLDs, "TLDID", "Typ");
        ViewBag.KlientID = new SelectList(db.Klienci, "KlientID", "Firma");
           var model = new Domena
            {
                Cena = cena.Cena
            };
        return View();
    }

But the Value is still 0.00. I have no idea how to accomplish this.

Any help would be very welcomed.


Edit after bcr answer :

I'm sorry I haven't put all the data needed. I have actually modified the httpget and httpPost methods since ive added another dropdownmenu to it. Here they are :

HTTPGET :

    public ActionResult Create()
    {
        ViewBag.TLDID = new SelectList(db.TLDs, "TLDID", "Typ");
        ViewBag.KlientID = new SelectList(db.Klienci, "KlientID", "Firma");
        ViewBag.StatusID = new SelectList(db.StatusDomeny, "StatusID", "Status");

        return View();
    }

HTTPPOST :

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Domena domena)
    {
        if (ModelState.IsValid)
        {
            db.Domeny.Add(domena);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.TLDID = new SelectList(db.TLDs, "TLDID", "Typ", domena.TLDID);
        ViewBag.KlientID = new SelectList(db.Klienci, "KlientID", "Firma", domena.KlientID);
        ViewBag.StatusID = new SelectList(db.StatusDomeny, "StatusID", "Status", domena.StatusID);
        return View(domena);
    }

My View looks like this :

    <div class="editor-label">
        @Html.LabelFor(model => model.TLDID, "TLD")
    </div>
    <div class="editor-field">
        @Html.DropDownList("TLDID", String.Empty)
        @Html.ValidationMessageFor(model => model.TLDID)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.KlientID, "Klient")
    </div>
    <div class="editor-field">
        @Html.DropDownList("KlientID", String.Empty)
        @Html.ValidationMessageFor(model => model.KlientID)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.StatusID, "Status")
    </div>
    <div class="editor-field">
        @Html.DropDownList("StatusID", String.Empty)
        @Html.ValidationMessageFor(model => model.StatusID)
    </div>

As of now, as you can see I've deleted anything related to "Cena" as I couldn't get it to work.

As I understand in the httpGet method the line :

model.TldDropDown = new SelectList(db.TLDs, "TLDID", "Typ");

should be

model.TldList = new SelectList(db.TLDs, "TLDID", "Typ");

based on what you've put in the CreateViewModel :

public IEnumerable<SelectListItem> TldList {get; set;}

Am I right ?

However, when I try this, im getting an error msg saying :

Cannot implicitly convert type 'System.Web.Mvc.SelectList' to IEnumearble. An explicit conversion exist. Are you missing a cast?

Maybe more explanation of what I'm trying to achive :

I have a Create page for Domena objects. There is a DropDownList for list of TLDs from db.TLDs listed by TLD.Typ. I want my httpGet / httpPost methods to know that if let's say TLDID = 1 (it's displayed TLD.Typ value from the DropDownList) was chosen then it should assign the value of "Cena" which belongs to TLDID = 1 to Domena.Cena property.

Hope that explains it better.

4

1 回答 1

1

感谢您的澄清,它有很大帮助。那么您的视图是否绑定到Domena实体作为其模型?这不在您的视图示例中,但我会假设是这样。

基本上,一旦您获得了用户选择的 TLD ID,您就需要从上下文中获取 TLD 实体,并且该 TLD 实体持有您要用来填充新 Domena 对象属性的 Cena 值。我不确定您是否想/在哪里将 Cena 值放在屏幕上,但在将新值保存到数据库DomenaViewModel后,您可以将其作为属性并在 POST 操作中设置它。Domena

假设Domena类是一个实体,使用实体作为视图模型并不是很好,正如这里多次讨论的那样。一般的方法似乎是使用DomenaViewModel类或DomenaDto类之类的东西作为视图模型。然后,您可以根据需要在视图模型和实体之间映射适当的字段。AutoMapper是帮助自动化和组织此过程的流行选项;我使用ValueInjecter.在这个特定的示例中,手动操作应该足够简单来说明这一点。

另一件事是ViewBag用于 ,SelectListsViewBag从未在 中引用View。我会在这里完全放弃使用ViewBag并坚持这种ViewModel方法。我将保持简单,重点关注 TLD 和 Domena 类,以及 Create 操作所需的内容。类似的方法将用于其他下拉列表和实体。

请注意,您要注意不要将另一个Domena与已经存在的数据库完全相同(具有所有相同的外键和值)添加到数据库中,除非这是您特别想要做的。这种下拉方法基于 Scott Allen 的文章

public class DomenaViewModel
{
    public List<TLD> Tlds {get; set;} 
    public int SelectedTldId { get; set; }

    public IEnumerable<SelectListItem> TldItems
    {
        get { return new SelectList(Tlds, "TLDID", "Typ"); }
    }

    // irrelevant code omitted
}

[HttpGet]
public ActionResult Create()
{
    var model = new DomenaViewModel
      {
          Tlds = db.TLDs.ToList();
      };

    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DomenaViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var tld = db.TLDs.Find(model.SelectedTldId); // assuming you're using DbContext
        if (tld != null)
        {
            // the mapping is best served in a different method, but we'll do it here for now
            var newDomena = new Domena
              {
                  TLD = tld,
                  Cena = tld.Cena
              }
            db.Domeny.Add(newDomena);
            db.SaveChanges();
        }
        return RedirectToAction("Index");
    }

    viewModel.Tlds = db.TLDs.ToList();
    return View(viewModel);
}

视图的相关部分:

@model DomenaViewModel

<div class="editor-field">
    @Html.DropDownListFor(m => m.SelectedTldId, Model.TldItems)
</div>
于 2013-05-15T17:24:36.787 回答