ASP.NET MVC IDENTITY_INSERT is set to OFF - asp.net-mvc

I have the following code in my HomeController:
public ActionResult Create()
{
return View();
}
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")]Article articleToCreate)
{
if (!ModelState.IsValid)
return View();
try
{
_db.AddToArticleSet(articleToCreate);
articleToCreate.posted = DateTime.Now;
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And this is the view for the Create Method
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="create">
<h2>Create News Article <span>( <%=Html.ActionLink("Cancel", "Index") %> )</span></h2>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="headline">Headline</label>
<%= Html.TextBox("headline") %>
</p>
<p>
<label for="story">Story <span>( HTML Allowed )</span></label>
<%= Html.TextArea("story") %>
</p>
<p>
<label for="image">Image URL</label>
<%= Html.TextBox("image") %>
</p>
<p>
<input type="submit" value="Post" />
</p>
</fieldset>
<% } %>
</div>
<!-- END div#create -->
</asp:Content>
The problem I get when I try and submit the data is an InnerException saying that the IDENTITY_INSERT is set to off. However the ID in my article table (which is called storyId) is set to Auto Increment, and is also set as Identity and also as primary key/index.
How do I fix this problem? Thanks.

Did you create the Linq To SQL DBML file and then change the Database Schema to all for Auto Increment? I'm thinking that you may have changed the schema but forgot to update the linq designer.
Just delete the table in the designer and re-drag it from the database.

Related

How do I view table data, fetched by linq to sql with table join?

How i can do view for such code, if i have join? in asp.net mvc on c# language
public ActionResult Details(int id)
{
var routeDetails = (from rd in db.Route
join rdd in db.RouteDetail
on rd.RouteId equals rdd.RouteId
where rd.RouteId == id
select new
{
RouteId = rd.RouteId,
Name = rd.Name,
Station = rdd.Station,
TimeArrival = rdd.TimeArrival,
TimeDeparture = rdd.TimeDeparture
}).First();
return View(routeDetails);
}
I can do view for one table without join, but how it will be with join?
here is how i do it without join for edit action:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Main.Master" Inherits="System.Web.Mvc.ViewPage<TrainShedule.Models.Route>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Edit</h2>
<% using (Html.BeginForm())
{%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<ul>
<li>Название маршрута:
<%= Html.TextBoxFor(m => m.Name) %>
<%= Html.ValidationMessageFor(m => m.Name)%>
</li>
</ul>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%= Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
You're creating an anonymous type for your routeDetails variable. If you want a strongly-typed view, you can define a new model class (RouteRouteDetail or similar) that contains the properties you want from both tables, and select instances of that type rather than selecting anonymous type instances using the new {} syntax.

Deleting record using MVC Delete View

What I am trying to do is I am Listing all the record and then provide option to delete the record. When User clicks on Delete Link on Index page he is redirected to Delete Confirmation Page( Delete View created by MVC framework), now what I was expecting was when I click on Submit button on the Delete View it will come to my Delete Action of Controller with the object that needs to be deleted. But the problem is I am getting a object but all the properties are set to null.
Below is the code:
//GET
public ActionResult DeleteUser (long id )
{
return View(_repository.GetUserById(id));
}
//POST
[HttpPost]
public ActionResult DeleteUser (UserDTO user)
{
_repository.DeleteUser(user.UserId);
/
return RedirectToAction("Index");
}
I was expecting that one submit is clicked then Second (HttpPost) method will be called and user will be filled with the values, but that is not happening..
can anyone tell me what wrong am I doing ???
This is my Delete View Code
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<RepositoryPatternSample.DTOs.UserDTO>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
DeleteUser
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>DeleteUser</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>UserDTO</legend>
<div class="display-label">UserId</div>
<div class="display-field"><%: Model.UserId %></div>
<div class="display-label">Username</div>
<div class="display-field"><%: Model.Username %></div>
<div class="display-label">FirstName</div>
<div class="display-field"><%: Model.FirstName %></div>
<div class="display-label">LastName</div>
<div class="display-field"><%: Model.LastName %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete User" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
</asp:Content>
Your properties are out of the form post. That's why you see the model null.
Personally instead of passing all the model properties I would pass only the id.
Something like that
<% using (Html.BeginForm()) { %>
<p>
<%: Html.HiddenFor(model=> model.UserId) %>
<input type="submit" value="Delete User" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
and your controller would be
[HttpPost]
public ActionResult DeleteUser (int userId)
{
_repository.DeleteUser(userId);
return RedirectToAction("Index");
}

Getting 404 on a simple controller

I'm creating a simple form to upload a file (which can be given a friendly name).
I've gone over this code time and time again, but always get a 404 when the form posts to /MyEntities/Add (this is a post-only URL on purpose).
Any thoughts would be much appreciated - I simply can't see what I've done wrong.
The controller:
public class MyEntitiesController : Controller
{
private DataFilesComparisonRepository repository = new DataFilesComparisonRepository();
public ActionResult Index()
{
List<MyEntitiesDataset> datasets = repository.GetMyEntitiesDatasets();
return View(datasets);
}
[HttpPost]
public ActionResult Add(HttpPostedFileBase postedFile, string friendlyName)
{
repository.AddMyEntities(friendlyName, postedFile.FileName, postedFile.InputStream);
return RedirectToAction("Index");
}
}
And the view:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<MyEntitiesDataset>>" %>
<%# Import Namespace="DataFilesComparison.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
The Title
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% Html.BeginForm("Add", "MyEntities", FormMethod.Post, new { enctype = "multipart/form-data" }); %>
<p>
<input type="file" name="postedFile" />
<label for="friendlyName">Friendly Name:</label>
<%= Html.TextBox("friendlyName") %>
<input type="submit" value="Add" />
</p>
<% Html.EndForm(); %>
<% if (Model == null || Model.Count == 0) { %>
<p>No datasets found.</p>
<% } else { %>
<ul>
<% foreach (MyEntitiesDataset dataset in Model) { %>
<li>
<%= dataset.Name %>
[<%= Html.ActionLink("X", "Delete", new { ID = dataset.ID })%>]
</li>
<% } %>
</ul>
<% } %>
</asp:Content>
The model you are passing into the view is not the same of the same type that you are posting back into the Add() method, which may be confusing the default routing settings. Although I see you have been explicit about which method to call, I have had problems like this before. Maybe try creating a ViewModel with the properties you need for the GET and POST, then using them in both the View and the Controller methods. Like this:
Model
public MyViewModel
{
public List<MyEntitiesDataset> Datasets {get; set;}
public HttpPostedFileBase PostedFile {get; set;}
public string FriendlyName {get; set;}
}
Controller Methods
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.Datasets = repository.GetMyEntitiesDatasets();
return View(datasets);
}
[HttpPost]
public ActionResult Add(MyViewModel model)
{
repository.AddMyEntities(model.FriendlyName, Model.PostedFile.FileName, Model.postedFile.InputStream);
return RedirectToAction("Index", model);
}
View
%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
<%# Import Namespace="DataFilesComparison.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
The Title
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% Html.BeginForm("Add", "MyEntities", FormMethod.Post, new { enctype = "multipart/form-data" }); %>
<p>
<input type="file" name="postedFile" />
<label for="Model.FriendlyName">Friendly Name:</label>
<%= Html.TextBoxFor(m => m.FriendlyName) %>
<input type="submit" value="Add" />
</p>
<% Html.EndForm(); %>
<% if (Model.Datasets == null || Model.Datasets.Count == 0) { %>
<p>No datasets found.</p>
<% } else { %>
<ul>
<% foreach (var dataset in Model.Datasets) { %>
<li>
<%= dataset.Name %>
[<%= Html.ActionLink("X", "Delete", new { ID = dataset.ID })%>]
</li>
<% } %>
</ul>
<% } %>
</asp:Content>
You might have to play around with the file uploader (not sure if there is an Html.FileFor, but hopefully you get the idea!
Good luck.

ASP.NET MVC and tinyMCE

I'm getting some very strange behaviour with tinyMCE in an ASP.NET MVC 2 beta app (same happend with MVC 1). I have a view called "edit.aspx" that is called when the user tries to create or edit an entity. The view uses jquery to load tinyMCE where ever it finds textarea's.
Here are my 2 action methods that both call the same "edit.aspx" view
public ActionResult Create()
{
return View("Edit", new FutureEvent());
}
[HttpGet]
public ActionResult Edit(int id)
{
FutureEvent futureEvent = (from fe in adminGalleryRepository.FutureEvents
where fe.ID == id
select fe).FirstOrDefault();
return View("Edit", futureEvent);
}
The "Edit.aspx" view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage<DomainModel.Entities.FutureEvent>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Future event
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(function() {
$("#tabs").tabs();
$('textarea').tinymce({
script_url: '../../Scripts/tiny_mce/tiny_mce.js',
theme: "advanced",
plugins: "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
// Theme options
theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true
});
});
</script>
<h2>Future event</h2>
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm("Edit", "FutureEvents")) {%>
<div id="tabs">
<ul>
<li>Future event</li>
</ul>
<div id="tabs-1">
<%= Html.Hidden("ID") %>
<label class="formLabel" for="Title">Title:
<%= Html.ValidationMessage("Title", "*") %>
<%= Html.TextBox("Title", Model.Title, new { size = "40px" })%>
</label>
<label class="formLabel" for="Info">Info:
<br />
<%= Html.TextArea("Info", Model.Info, 15, 130, null) %>
</label>
<br />
<label class="formLabel" for="WebSite">Web site address:
<%= Html.TextBox("WebSite", Model.WebSite, new { size = "40px" })%>
</label>
</div>
</div>
<div class="clear" ></div>
<div id="footer" style="text-align: left">
<input type="submit" value="Save" />
<%=Html.ActionLink("Back to List", "List") %>
</div>
<% } %>
</asp:Content>
The strange thing is that the create method renders the "edit" view and the tinyMCE edit appears correctly. But when the edit action method renders the "edit" view, the view appears as you would expect - but without the tinyMCE editor.
No errors appear in FireBug, I get exactly the same behaviour in IE.
I also tried removing the $("#tabs").tabs() line but it made no difference.
It could be related to this line:
script_url: '../../Scripts/tiny_mce/tiny_mce.js',
Since the problem is in the Edit view, maybe the extra parameter adds one level to the folder structure.
Why don't you try:
script_url: '/Scripts/tiny_mce/tiny_mce.js',

MVC - Partial Views

I have a Viewpage menu with controller Menucontroller. I have a partialView ViewItems which is strongly typed as object BagItem with contro ller BagItem.
I am trying to render the partial View from View page(Menu.aspx) and can't render partial View. Any help would be greatly appreciated.New to MVC. Here is the code
Menu.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MenuItem>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
OrderMenu
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
OrderMenu</h2>
<div>
<table>
<tr>
<td>
<% List<BagItem> sb = new List<BagItem>(); %>
<% Html.RenderPartial("../ShoppingBagItem/ViewItems", sb, (ViewDataDictionary)ViewData["BagItems"]);%>
</td>
</tr>
</table>
</div>
partialView
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<GuessCafe.Library.BagItem>>" %>
<body>
<div id="divLatestStocks">
<%foreach (var item in Model)
{ %>
<ul>
<li>
<%= item.ShoppingBagItemId %>
</li>
</ul>
<%}
%>
</div>
</body>
BagItemController
public ActionResult GetShoppingBagItems()
{
ViewData["BagItems"] = ObjectContext.BagItem.ToList();
return View(ViewData["BagItems"]);
}
I think what you want is simply this:
<% Html.RenderPartial("ViewItems", ViewData["BagItems"]); %>
This is assuming your partial view is named ViewItems.ascx.
You can remove the following line from your view:
<% List<BagItem> sb = new List<BagItem>(); %>
Update: your partial view should not contain <body>...</body> tags. These should either be on the master page.
public ActionResult GetShoppingBagItems()
{
ViewData["BagItems"] = ObjectContext.BagItem.ToList();
return View(ViewData["BagItems"]);
}
This is a bad practice at all. If you want pass Model to view why just use ViewData Dictionary ?
You can simply write :
public ActionResult GetShoppingBagItems()
{
var BagItems = ObjectContext.BagItem.ToList();
return View(BagItems);
}

Resources