したがって、私はMVC3に移動しました。私はcodefirstのアプローチも本当に好きです。新しいレコードを保存するときにモデルの[Key]プロパティを設定できません
これで私は少し気になりましたが、MVC2ではレコードを追加して編集することができましたが、今はできません。
私はそれがあいまいなスタートであることを知っています。
namespace ESF_ResourceManager.Controllers
{
public class FileListController : ResourceManagerController
{
//
// GET: /FileList/
public ActionResult Index()
{
var fileList = from fl in DBContext.FileLists
where fl.FileListID > 0
select fl;
return View(fileList.ToList());
}
//
// GET: /FileList/Create
[HttpGet]
public ActionResult Create()
{
return View();
}
//
// POST: /FileList/Create
[HttpPost]
public ActionResult Create(FileList fileDetail)
{
if (ModelState.IsValid)
{
// test the file - size only - the file type should have been checked via Extensions as par tof the model definition
if (fileDetail.FileUrl.ContentLength > 0 && fileDetail.FileUrl.ContentLength < 1048576)
{
string fileName = Path.GetFileName(fileDetail.FileUrl.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads/documents"), fileName);
fileDetail.FileUrl.SaveAs(path);
DBContext.FileLists.Add(fileDetail);
DBContext.SaveChanges();
return RedirectToAction("Index");
}
}
return View(fileDetail);
}
//
// GET: /FileList/Edit/5
[HttpGet]
public ActionResult Edit(int id)
{
var fileDetail = from fl in DBContext.FileLists
where fl.FileListID == id
select fl;
return View(fileDetail.Single());
}
//
// POST: /FileList/Edit/5
[HttpPost]
public ActionResult Edit(int id, FileList fileDetail)
{
if (ModelState.IsValid)
{
var fileEdited = DBContext.FileLists.Find(id);
UpdateModel(fileEdited);
DBContext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
//
// GET: /FileList/Delete/5
public ActionResult Delete(int id)
{
var fileDetail = from fl in DBContext.FileLists
where fl.FileListID == id
select fl;
return View(fileDetail.Single());
}
//
// POST: /FileList/Delete/5
[HttpPost]
public ActionResult Delete(int id, FileList fileDetail)
{
try
{
DBContext.FileLists.Remove(DBContext.FileLists.Find(id));
DBContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
かみそりであるビューが(作成のため)されている:
@model ESF_ResourceManager.Models.FileList
@{
ViewBag.Title = "File List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Create", "FileList", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>File List</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FileTitle)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FileTitle)
@Html.ValidationMessageFor(model => model.FileTitle)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FileUrl)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.FileUrl, new { type = "file" })
@Html.ValidationMessageFor(model => model.FileUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
ここ
は私のモデルの一
namespace ESF_ResourceManager.Models
{
public class FileList
{
[Key]
public int FileListID { get; set; }
[DisplayName("File title: ")]
[Required(ErrorMessage = "Please set a unique title for the file")]
// TODO: Need to add remote validation - must be unique
public string FileTitle { get; set; }
[DisplayName("Choose a File")]
[FileExtensions(Extensions = "txt, zip, pdf, ppt, xls, doc, docx, xlsx, pptx", ErrorMessage = "Please choose a valid file of type txt, zip, pdf, ppt, xls, doc, docx, xlsx or pptx")]
public HttpPostedFileBase FileUrl { get; set; }
}
}
そして対応するコントローラの一例ですしたがって、ビューをロードしてデータを入力するフォームを表示できますが、[作成]ボタンをクリックすると、次のメッセージが表示されます:
値をnullにすることはできません。パラメータ名:キー
私はデバッガでオブジェクトを見ていますが、create post関数に入るオブジェクトの何もnullではありません。キーが0で、これが1になる(おそらく間違っている)ことが予想されます。
ここで私の最初の質問は何ですか?これが私にとって適切に機能するためには、私は何をする必要がありますか?
2番目の質問はより一般的です - 私のデータはどこですか?私がこれを読んだチュートリアルでは、SQLExpressデータベースがApp_Data内の場所またはSqlCEを作成したことを示唆しています。どちらも見つけることができないので、私はこれがどこにあるのか混乱しています。
これに関するお手伝いがあれば幸いです。
感謝 nathj07
EDITによって停止するための
おかげで、私はまだ質問をする際に含めることが参考になるものを学んでいます。だから、ここで要求された項目は以下のとおりです。
データコンテキスト
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace ESF_ResourceManager.Models
{
public class ResourceManagerContext : DbContext
{
public DbSet<Resource> Resources { get; set; }
public DbSet<ResourceType> ResourceTypes { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<FileList> FileLists { get; set; }
}
}
のWeb.Config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
そして最後に -
ビュー/ Web.configファイル
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
その他の情報が必要な場合は、喜んで投稿します。
おかげ nathj07
編集2 私は今、手動から[SQLExpressデータベースを追加し、web.configファイル内の接続文字列を更新しようとしています。
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|DB_ESF_ResourceManager.mdf;User Instance=true" />
</connectionStrings>
これは私に同じエラーを残します。全く違いはありません。私はこれで完全な喪失に陥っていますし、どこでそれに行くのか分かりません。これ以上の提案はありますか?あなたのweb.configファイル内の任意の接続文字列を持っていないので
:あなたはあまりにも必要
おかげ nathj07
2つの以上のもの。あなたが明示的に接続文字列を指定した場合は、設定してください –
今は厄介な問題は何ですか?上記の例外(私はメッセージを強調表示しました)?または、データベースを見つけられない、または作成できないことはありますか? – Slauma
問題はありません。基本的に私はこの作品を作り直しました。プロジェクトには、リソースタイプ、リソース、ユーザー、ファイルリストの4つのモデルがありました。ファイルリストをすべて再作成したら、すべてがうまく動いていることがわかりました。私は示されているようにファイルリストモデルを追加し、私はエラーを取得します。今回は接続文字列がなく、DBServerがSQLServerExpressまたはCEのいずれかに作成されていると思います。私は今他のいくつかの質問が残っていますが、私はそれらを新しいスレッドに投稿します。すべての助けに感謝します。私はそれに応じてupvoteします nathj07 – nathj07