只有defalt值传递给数据库

时间:2017-05-27 12:07:43

标签: asp.net-mvc entity-framework-6

我对编程非常陌生,而且我非常简单地使用#34;创建"控制器和视图。

在视图中,用户声明值,应该传递给数据库。这是模特:

public class Expense

{
    public int ExpenseID { get; set; }

    [DisplayName("Data")]
    [Column(TypeName = "DateTime2")]
    public DateTime Date { get; set; }

    [DisplayName("Wartość")]
    public decimal Amount { get; set; }

    [DisplayName("Opis")]
    public string Details { get; set; }

    [DisplayName("Rodzaj")]
    public int CategoryID { get; set; }

    public virtual Category Category { get; set; }

}

public class Category
    {
        public int CategoryID { get; set; }

        public string Name { get; set; }

        public virtual ICollection<Expense> Expenses { get; set; }
    }

在同一视图中,我想要包含用于管理类别的部分视图(添加,删除)。

为了实现这一点,我实施了ViewModel:

 public class ExpenseCreateViewModel
{
    public Expense ExpenseCreate { get; set; }
    public Category CategoryCreate { get; set; }
}

以下是我的观点代码:

@model Wydatki2._0.Models.ExpenseCreateViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Dodaj wydatek</h2>


<table class="table">
<tr>
    <th>
        <div>
            @using (Html.BeginForm("CreateExpense", "ExpenseCreate", FormMethod.Post, new { }))
            {
                @Html.AntiForgeryToken()

                <div class="form-horizontal">

                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    <div class="form-group">
                        @Html.LabelFor(model => model.ExpenseCreate.CategoryID, "Rodzaj", htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">

                            @Html.DropDownList("CategoryID", null, htmlAttributes: new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.ExpenseCreate.CategoryID, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.ExpenseCreate.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.ExpenseCreate.Amount, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.ExpenseCreate.Amount, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.ExpenseCreate.Date, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.ExpenseCreate.Date, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.ExpenseCreate.Date, "", new { @class = "text-danger" })
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.ExpenseCreate.Details, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.ExpenseCreate.Details, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.ExpenseCreate.Details, "", new { @class = "text-danger" })
                        </div>
                    </div>



                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Dodaj" class="btn btn-default" />
                        </div>
                    </div>
                </div>
            }
        </div>
    </th>
<th>
    <div>
        <input type="button" id="btn" class="btn btn-default" value="Dodaj/Usuń Kategorię" />
        <p class="error">@ViewBag.Warning</p>
    </div>

    <div id="Create" style="display:none">
        @Html.Partial("CreateCategory", Model.CategoryCreate)
    </div> 


</th>
</tr>
</table>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/toggle")
}

问题是,当我提交表单时,只能正确传递CategoryID值。其余参数只有默认值。部分视图效果很好 - 我可以添加或删除类别,然后将其传递到主视图。

我的控制器的代码:

namespace Wydatki2._0.Controllers
{
    public class ExpenseCreateController : Controller
    {
        private WydatkiContext db = new WydatkiContext();




        public ActionResult Create(bool? warn = false)
        {
            ExpenseCreateViewModel model = new ExpenseCreateViewModel()
            {
                ExpenseCreate = new Expense(),
                CategoryCreate = new Category()
            };

            var query = from b in db.Categories
                        where b.CategoryID != 1
                        select b;



            if (warn.GetValueOrDefault())
            {
                ViewBag.Warning = "Nie możesz usunąć tej kategorii.";
            }

            ViewBag.CategoryID = new SelectList(query, "CategoryID", "Name");
            return View(model);
        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateExpense([Bind(Include = "ExpenseID,Date,Amount,Details,CategoryID")] Expense expense)
        {
            if (ModelState.IsValid)
            {
                db.Expenses.Add(expense);
                db.SaveChanges();

                return RedirectToAction("Create");
            }

            var query = from b in db.Categories
                        where b.CategoryID != 1
                        select b;

            ViewBag.CategoryID = new SelectList(query, "CategoryID", "Name", expense.CategoryID);
            return View(expense);
        }




        public ActionResult CreateCategory()
        {

            return View();
        }




        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateCategory([Bind(Include = "CategoryID,Name")] Category category)
        {


            if (ModelState.IsValid)
            {
                Category cat = db.Categories.FirstOrDefault(c => c.Name== category.Name);



                if (cat != null)
                {
                    if (cat.CategoryID == 1 || cat.CategoryID ==2)

                    {
                        return RedirectToAction("Create", new { warn = true });
                    }
                    else
                    {
                        db.Categories.Remove(cat);
                        db.SaveChanges();
                        return RedirectToAction("Create");
                    }
                }

                else
                {

                    db.Categories.Add(category);
                    db.SaveChanges();

                    return RedirectToAction("Create");
                }
            }

            return View(category);
        }

我倾向于认为这个问题是由我传递给视图的模型引起的,但我真的不知道,如何正确传递...任何人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

你应该使用

([Bind(Prefix="prefixhere")]Category category)

我认为您的前缀应为CategoryCreate类别,您的模型ExpenseCreateViewModel的扩展名与您的CreateExpense相同,您的前缀应为ExpenseCreate,这样您就可以告诉控制器期望您的输入名称在此前缀之后,因此它将在您传递的前缀后的创建类别操作中查找CategoryID and Name

像这样的东西

([Bind(Prefix="CategoryCreate")]Category category)
([Bind(Prefix="ExpenseCreate")]Expense expense)