0

Asp.net MVC4 アプリケーションに管理領域を追加したので、自分は初心者レベルの開発者だと思います。私の edit [HttpGet] アクションは、アセットの値を返すため、正常に動作しています。私はたくさんの MVC4 スペシャルをオンラインで調べましたが、それらのほとんどは [HttpPost] Edit メソッドに次を使用します。

    [HttpPost]
    public ActionResult Edit(ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel models)
    {
        try
        {
            if (ModelState.IsValid)
            {
                _entities.Entry(models).State = EntityState.Modified;
                _entities.SaveChanges();
                return RedirectToAction("Index", new { ID = models.ID });
            }
        }
        catch (DataException)
        {

            ModelState.AddModelError("", "Unable able to save changes....epic fail!!!");
        }

        return View(models);
    }

問題は、次の.Entryを使用するアクセス権がないことです。

_entities.Entry(models).State = EntityState.Modified; 

それを使用できるようにする参照が明らかにありませんが、それが何であるかはわかりません。

これが私のViewModelです(私はDbContextを使用していましたが、使用しませんでした):

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using ITTESI.AssetTracker.Web.UI.Content.Classes;

namespace ITTESI.AssetTracker.Web.UI.ViewModels
{    
public class AssetDetailsViewModel    
{        
    public int ID { get; set; }
    public string AssetIdentifier { get; set; }
    public string ManufacturerName { get; set; }
    public string Model { get; set; }
    public string SchoolLocation { get; set; }        
    public string Status { get; set; }
    public string Condition { get; set; }
    // [DataType(DataType.MultilineText)]
    public string Notes { get; set; }
    public Utils.AssignReturn AssignReturnEligible { get; set; }

    public string SchoolLocationCd { get; set; }
    public string SchoolLocationDisplayValue { get; set; }        

    public AssignedUserViewModel AssignedUserViewModelObj { get; set; }
}
}

これが私の管理コントローラーです:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Metadata.Edm;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using ITTESI.AssetTracker.Data.EntityModel.Entity;
using ITTESI.AssetTracker.Data.EntityModel.Definition;
using System.Data.Entity;
using ITTESI.AssetTracker.Web.UI;
using ITTESI.AssetTracker.Web.UI.Content;
using ITTESI.AssetTracker.Web.UI.Content.Classes;
using ITTESI.AssetTracker.Web.UI.ViewModelBuilders;
using ITTESI.AssetTracker.Web.UI.ViewModels;

namespace ITTESI.AssetTracker.Web.UI.Controllers
{
    public class AdminController : Controller
    {


        ExtendedITTESI_AssetTrackerEntities _entities = new ExtendedITTESI_AssetTrackerEntities();

        public ActionResult Index(ViewModels.AssetDetailsViewModel assetDetails)
        {
            ViewBag.PageTitle = "Admin Search";
            ViewBag.HideShowLocation = "hide";
            ViewBag.SubmitButtonValue = "Search";
            return View("Index", assetDetails);
        }

        [HttpGet]
        public ActionResult Edit(ITTESI_AssetTracker_Asset asset) // 'ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel'
        {
            ViewBag.PageTitle = "Edit Asset";
            ViewBag.SubmitButtonValue = "Save";
            ViewBag.ShowLocation = true;

            var model = _entities.ITTESI_AssetTracker_Asset.FirstOrDefault();
            return View(model);
        }

        [HttpPost]
        //public ActionResult Edit(ExtendedITTESI_AssetTrackerEntities ate)
        public ActionResult Edit(ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel models)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _entities.Entry(models).State = EntityState.Modified;
                    _entities.SaveChanges();
                    return RedirectToAction("Index", new { ID = models.ID });
                }
            }
            catch (DataException)
            {

                ModelState.AddModelError("", "Unable able to save changes....epic fail!!!");
            }

            return View(models);
        }
    }
}

ここに私の編集ビューがあります:

@model ITTESI.AssetTracker.Data.EntityModel.Entity.ITTESI_AssetTracker_Asset

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

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

    <fieldset>
        <legend>ITTESI_AssetTracker_Asset</legend>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

また、問題は、ExtendedITTESI_AssetTrackerEntities の DbContext が存在せず、System.Data.Entity の一部であるもう少し調査した結果であることも確かです。ExtendedITTESI_AssetTrackerEntitiesの唯一のコードは次のとおりです。

using System;
using Common.Logging;
using EFCachingProvider;
using EFCachingProvider.Caching;
using EFProviderWrapperToolkit;
using EFTracingProvider;
using ITTESI.AssetTracker.Data.EntityModel.Entity;

namespace ITTESI.AssetTracker.Data.EntityModel.Definition
{
    public class ExtendedITTESI_AssetTrackerEntities : ITTESI_AssetTrackerEntities
    {
        private ILog logOutput;

        public ExtendedITTESI_AssetTrackerEntities()
            : this("name=ITTESI_AssetTrackerEntities")
        {
        }

        public ExtendedITTESI_AssetTrackerEntities(string connectionString)
            : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
                    connectionString,
                    "EFTracingProvider",
                    "EFCachingProvider"
            ))
        {
            CachingPolicy = AssetTrackerEntitiesCachingPolicy.CachingPolicy();
            Cache = AssetTrackerEntitiesCache.Cache();
        }

        #region Tracing Extensions

        private EFTracingConnection TracingConnection
        {
            get { return this.UnwrapConnection<EFTracingConnection>(); }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandExecuting
        {
            add { this.TracingConnection.CommandExecuting += value; }
            remove { this.TracingConnection.CommandExecuting -= value; }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandFinished
        {
            add { this.TracingConnection.CommandFinished += value; }
            remove { this.TracingConnection.CommandFinished -= value; }
        }

        public event EventHandler<CommandExecutionEventArgs> CommandFailed
        {
            add { this.TracingConnection.CommandFailed += value; }
            remove { this.TracingConnection.CommandFailed -= value; }
        }

        private void AppendToLog(object sender, CommandExecutionEventArgs e)
        {
            if (this.logOutput != null)
            {
                this.logOutput.Debug(e.ToTraceString().TrimEnd());

            }
        }

        public ILog Log
        {
            get { return this.logOutput; }
            set
            {
                if ((this.logOutput != null) != (value != null))
                {
                    if (value == null)
                    {
                        CommandExecuting -= AppendToLog;
                    }
                    else
                    {
                        CommandExecuting += AppendToLog;
                    }
                }

                this.logOutput = value;
            }
        }


        #endregion

        #region Caching Extensions

        private EFCachingConnection CachingConnection
        {
            get { return this.UnwrapConnection<EFCachingConnection>(); }
        }

        public ICache Cache
        {
            get { return CachingConnection.Cache; }
            set { CachingConnection.Cache = value; }
        }

        public CachingPolicy CachingPolicy
        {
            get { return CachingConnection.CachingPolicy; }
            set { CachingConnection.CachingPolicy = value; }
        }

        #endregion
    }
}

DbContext を使用してモデルを作成する必要があるかもしれません。

.Entry 以外は使用できますか? 助けていただきありがとうございますが、アプリの設定方法では、編集内容をデータベースに適切に保存する方法がわかりません。

4

1 に答える 1

0

Edit アクションの .Entry 以外にも方法があります。EF は非常に賢いので、データベースから ID でオブジェクトをフェッチし、すべてのプロパティを手動で変更できます。元:

[HttpPost]
public ActionResult Edit(ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel models)
{
    try
    {
        if (ModelState.IsValid)
        {
            ITTESI.AssetTracker.Web.UI.ViewModels.AssetDetailsViewModel temp = _entities.dbname.firstOrDefault(x = > x.ID == models.ID);
            temp.AssetIdentifier = models.AssetIdentifier ;
            temp.ManufacturerName = models.ManufacturerName ;
            .
            .
            .
            _entities.SaveChanges();
            return RedirectToAction("Index", new { ID = models.ID });
        }
    }
    catch (DataException)
    {

        ModelState.AddModelError("", "Unable able to save changes....epic fail!!!");
    }

    return View(models);
}

EF は、変更するエンティティを理解し、"_entities.saveChanges();" で更新します。これがうまくいくかどうかはわかりませんが、試してみる価値はあると思います

于 2013-10-31T16:32:03.927 に答える