Pergunta

The problem: I followed the tutorial here and I can pull data from the database. I can also Delete records from the database. But when I try to create or edit I get this error:

Invalid Value

So as I was looking in the controller and I see that there is ModelState.IsValid is when I set a breakpoint to it, it is always false.

Here is my model:

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Data.Entity; 
using System.Linq; 
using System.Web;

namespace MvcApplication1.Models 
{
    public class Text
    {
       [Key]
       public int id { get; set; }
       [Required]
       public string text { get; set; }
    }

    public class textDBContext : DbContext
    {
       public DbSet<Text> texts { get; set; }
    } 
}

My Database has two fields: "id" and "text". "id" is of datatype int and "text" is of datatype string.

I generated this controller from the model which also generated the views (CRUD)

Here is my controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class textDBController : Controller
    {
        private textDBContext db = new textDBContext();

        //
        // GET: /textDB/

        public ActionResult Index()
        {
            return View(db.texts.ToList());
        }

        //
        // GET: /textDB/Details/5

        public ActionResult Details(int id = 0)
        {
            Text text = db.texts.Find(id);
            if (text == null)
            {
                return HttpNotFound();
            }
            return View(text);
        }

        //
        // GET: /textDB/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /textDB/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Text text)
        {
            if (ModelState.IsValid)
            {
                db.texts.Add(text);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(text);
        }

        //
        // GET: /textDB/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Text text = db.texts.Find(id);
            if (text == null)
            {
                return HttpNotFound();
            }
            return View(text);
        }

        //
        // POST: /textDB/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Text text)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors);


                // Breakpoint, Log or examine the list with Exceptions.
            }
            if (ModelState.IsValid)
            {
                db.Entry(text).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(text);
        }

        //
        // GET: /textDB/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Text text = db.texts.Find(id);
            if (text == null)
            {
                return HttpNotFound();
            }
            return View(text);
        }

        //
        // POST: /textDB/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Text text = db.texts.Find(id);
            db.texts.Remove(text);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Here is the edit view:

@model MvcApplication1.Models.Text

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Text</legend>

        @Html.HiddenFor(model => model.id)

        <div class="editor-label">
            @Html.LabelFor(model => model.text)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.text)
            @Html.ValidationMessageFor(model => model.text)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

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

What am I doing wrong here?

Foi útil?

Solução 3

I think the property name, class name, and argument name all being the same is messing up the MVC model-binding magic. If you change:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Text text)

to:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Text values)

it posts back correctly.

Outras dicas

If class name and property name is same then model binding is not mapping perperly. [HttpPost] public ActionResult TextView(Text objtext,string text) { return View(); } Here you can check, objText will get the data , and text also will get the data from textbox. Hope it will work for you.

This may solve the problem:- code this at bottom of View

    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top