Display Error message on same view - asp.net-mvc

I'm trying to delete a record from the database using MVC 2. currently delete function works fine but there are some records with foreign key relations so i don't wont them to be deleted and when user try to delete such a record i want to show a error message on the delete view without navigating to another view.
Controller:
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
StockRepository rep = new StockRepository();
Stock stock = rep.GetStock(id);
rep.Delete(stock);
rep.Save();
return RedirectToAction("Index");
}
catch
{
//need to display an error message if unable to delete
return View();
}
}
View:
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Fields</legend>
<div class="display-label">StockID</div>
<div class="display-field"><%: Model.StockID %></div>
<div class="display-label">ClientName</div>
<div class="display-field"><%: Model.ClientName %></div>
<div class="display-label">ItemName</div>
<div class="display-field"><%: Model.ItemName %></div>
<div class="display-label">ItemCount</div>
<div class="display-field"><%: Model.ItemCount %></div>
<div class="display-label">Price</div>
<div class="display-field"><%: String.Format("{0:F}", Model.Price) %></div>
<div class="display-label">OtherExpences</div>
<div class="display-field"><%: String.Format("{0:F}", Model.OtherExpences) %></div>
<div class="display-label">TotalStockValue</div>
<div class="display-field"><%: String.Format("{0:F}", Model.TotalStockValue) %></div>
<div class="display-label">DeliveryDate</div>
<div class="display-field"><%: String.Format("{0:d}", Model.DeliveryDate) %></div>
<div class="display-label">Description</div>
<div class="display-field"><%: Model.Description %></div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>

Using Viewdata
View
<%
if (ViewData["dbError"] != null)
{
%>
//display ViewData dbError
<%
}
%>
Controllor
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
StockRepository rep = new StockRepository();
Stock stock = rep.GetStock(id);
rep.Delete(stock);
rep.Save();
return RedirectToAction("Index");
}
catch
{
//need to display an error message if unable to delete
**ViewData["dbError"] = "Error message here";**
return View();
}
}

Related

Cannot apply indexing with [] to an expression of type 'HttpRequest'

I am trying to get a value from a textbox of my View.
This is my View:
#model MyDataIndexViewModel
#{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email})
</div>
</div>
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="btn btn-default pull-right" href="/ChangeMyData/Save">Speichern</a>
</div>
</div>
This is my Controller:
[HttpPost]
public ActionResult Save()
{
var email = Request["txtEmail"].ToString();
return View();
}
I get the error just as it says in the Title.
Thank you in advance!
VIEW:
#model MyDataIndexViewModel
#using (Html.BeginForm("Save", "CONTROLLER_NAME"))
{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email, id="txtEmail"})
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="submit btn btn-default pull-right">Speichern</a>
</div>
</div>
}
CONTROLLER
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
You can either use strongly-typed viewmodel binding:
View
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBox("txtEmail", Model.Email)
Controller
[HttpPost]
public ActionResult Save(MyDataIndexViewModel model)
{
var email = model.Email;
return View();
}
Or use a TextBoxFor directly for model binding:
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBoxFor(model => model.Email)
Or if you still want to use HttpRequest members, Request.Form collection (a NameValueCollection) is available to retrieve text from txtEmail input:
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
Note that Request["txtEmail"] is discouraged due to no compile time safety applied for it, because the key value may retrieved from Request.QueryString, Request.Form or other HttpRequestBase members.
Similar issue:
MVC TextBox with name specified not binding model on post
Access form data into controller using Request in ASP.NET MVC

Store an image to a database using Entity Framework

I would like to save an image (from file, png or jpg) to the database using Entity Framework.
My code is here:
[HttpPost]
public ActionResult Create(Food fd)
{
try
{
FoodOrderEntities fo = new FoodOrderEntities();
Stream inpStream = Request.InputStream;
Int32 length = Convert.ToInt32(inpStream.Length);
byte[] tempImage = new byte[length];
inpStream.Read(tempImage, 0, length);
//FoodImage is an image field in the datatable, mapped by the Entity Framework
fd.FoodImage = tempImage;
fo.AddToFood(fd);
fo.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
My view is:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<% using (Html.BeginForm("Create","Food",FormMethod.Post,new {enctype="multipart/form-data"})) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.FoodName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FoodName) %>
<%: Html.ValidationMessageFor(model => model.FoodName) %>
</div>
<div>
Select a file: <input type="file" name="fileUpload" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
But, using Request.Files["fileUpload"] I got only null. Then, I have used this code, but I could get only 124 bytes from my image. Instead inpStream.Length I have used Request.TotalBytes and Request.ContentLength, but with the same result. Please, help me! Thank you in advance.
Best regards,
alenan13

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");
}

ASP.NET MVC Model State Validations

<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>
</div>
<% using (Html.BeginForm("Register", "Account" , FormMethod.Post))
{ %>
<div>
<fieldset>
<legend>Account Information</legend>
<p>
<label for="username">User Name:</label>
<%= Html.TextBox("username") %>
<%= Html.ValidationMessage("username") %>
</p>
<p>
<label for="FirstName">First Name</label>
<%= Html.TextBox("firstName") %>
<%= Html.ValidationMessage("firstName") %>
</p>
<p>
<label for="LastName">Last Name</label>
<%= Html.TextBox("lastName") %>
<%= Html.ValidationMessage("lastName") %>
</p>
<p>
<label for="email">Email:</label>
<%= Html.TextBox("email") %>
<%= Html.ValidationMessage("email") %>
</p>
<p>
<label for="password">Password:</label>
<%= Html.Password("password") %>
<%= Html.ValidationMessage("password") %>
</p>
<p>
<label for="confirmPassword">Confirm password:</label>
<%= Html.Password("confirmPassword") %>
<%= Html.ValidationMessage("confirmPassword") %>
</p>
<p>
<label for="Role">Role:</label>
<%= Html.DropDownList("Role",((SelectList)ViewData["Roles"]),"--Select One---") %>
</p>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
<% } %>
private ModelStateDictionary _modelState;
public AccountController() : this(null, null)
{
_modelState = new ModelStateDictionary();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string username, string firstName, string lastName, string password, string confirmPassword, string email, string role)
{
try
{
if (string.IsNullOrEmpty(password))
_modelState.AddModelError("password", "passowrd field is empty");
if (string.IsNullOrEmpty(confirmPassword))
_modelState.AddModelError("confirmPassword", "Confim Passowrd field is empty");
if (string.IsNullOrEmpty(username))
_modelState.AddModelError("username", "UserName field is empty");
if (string.IsNullOrEmpty(email))
_modelState.AddModelError("email", "Email field cannot be empty");
Regex regEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!regEmail.IsMatch(email))
_modelState.AddModelError("email", " The email id submitted is not in valid format");
if (string.IsNullOrEmpty(firstName))
_modelState.AddModelError("firstName", "First name field is empty");
if (string.IsNullOrEmpty(lastName))
_modelState.AddModelError("lastName", "Last name field is empty");
if (!password.Equals(confirmPassword, StringComparison.InvariantCultureIgnoreCase))
_modelState.AddModelError("password", "Password do not match");
if (_modelState.IsValid)
{
int id = _UsrService.GetRoleId(role);
Data.User usr = new User(username, firstName, lastName, email, DateTime.Now, null, id);
string retRegister = _UsrService.RegisterUser(usr, password, confirmPassword, "none", "none");
if (retRegister.Equals("true"))
{
UserRolesControl contrl = new UserRolesControl(Users(), Roles());
return View("Control", contrl);
}
else
{
ModelState.AddModelError("_Form", retRegister);
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
var roles = _UsrService.GetRoles().ToList();
ViewData["Roles"] = new SelectList(roles);
return View();
}
}
else
{
var roles = _UsrService.GetRoles().ToList();
ViewData["Roles"] = new SelectList(roles);
return View();
}
}
catch (Exception ex)
{
return View();
}
}
Above is a registrations form, I am working on validations on it. It does run through fine in the controller method , but it does not display the error messages when it send back to register page. It there anything wrong with my code?
What's _modelState? Why not use ModelState instead?
Or just Data Annotations for client side validation as well.
In this code, you are not returning the ModelState, that is why no errors are showing. Just use ModelState instead of _modelState, and you should be all set.:
if (_modelState.IsValid)
{
//blah
}
else
{
var roles = _UsrService.GetRoles().ToList();
ViewData["Roles"] = new SelectList(roles);
return View();
}

ASp.NET MVC: TryUpdateModel doesn't update all properties

I've got the following action:
public ActionResult Create()
{
var entity = new Employee();
TryUpdateModel(entity, new[] { "Person.Name", "Code", "CompanyID" });
if (ModelState.IsValid)
{
var result = Service.MergeEmployee(entity);
return RedirectToAction("List", new { success = true });
}
return View("Edit", new SupplierEmployeeModel() { Employee = entity });
}
What happens is that the property "Person.Name" doesn't get filled by the TryUpdateModel.
This is my form:
<fieldset>
<p>
<label for="Name"><%=Strings.NAME %></label>
<%= Html.TextBox("Person.Name", Model.Employee.Person.Name, new { Class = "text" })%>
<%= Html.ValidationMessage("Name", "*") %>
</p>
<p>
<label for="CompanyID"><%=Strings.SUPPLIER %></label>
<%= Html.DropDownList("CompanyID") %>
<%= Html.ValidationMessage("CompanyID", "*")%>
</p>
<p>
<label for="Code"><%=Strings.CODE %></label>
<%= Html.TextBox("Code", Model.Employee.Code)%>
<%= Html.ValidationMessage("Code", "*") %>
</p>
<p>
<%= Html.Hidden("ID", Model.Employee.ID)%>
</p>
<div id="tabs-DE-actions" class="ui-dialog-buttonpane ui-helper-clearfix" style="display: block;">
<button class="ui-state-default ui-corner-all" type="submit"><%=Strings.SAVE%></button>
</div>
</fieldset>
Any thoughts on why this is happening?
Thanks
Make sure the Person object is initialized in the Employee constructor; if it's null to begin with it is probably not updated properly.
public Employee()
{
Person = new Person();
}
Try this:
TryUpdateModel(entity,"Person", new[] { "Name", "Code", "CompanyID" });
In order to fill in Person.Name, the model binder has to create a new Person. Have you given the model binder enough info to do that? Alternately, try creating the Person yourself before binding.

Resources