I have bind the data using grid in asp.net mvc3. I have a problem in edit link in the bind table. If I click on edit link it's not responding. Here's what I have:
Teacher.cs
public class Teacher
{
public static List<Teacher> GetList { get; set; }
public int T_Id { get; set; }
public string T_Name { get; set; }
public string T_Address { get; set; }
public string Sub_Id { get; set; }
}
Teachercontroller
public ActionResult Edit(int id,string T_Name,string T_Address,string Sub_Id)
{
// Teacher list= new Teacher();
var edit = EditList();
//list.T_Id = Convert.ToInt32(T_Id);
return View(edit);
}
[HttpPost]
public ActionResult EditList()
{
var editlist = new List<Teacher>();
using (SqlConnection conn = new SqlConnection(#"Integrated ecurity=SSPI;Persist Security Info=False;Initial Catalog=Demo;Data Source=CIPL41\SQLEXPRESS"))
{
conn.Open();
var modeledit = new Teacher();
SqlCommand cmd = new SqlCommand("edit", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#T_Id", modeledit.T_Id);
cmd.Parameters.AddWithValue("#T_Name", modeledit.T_Name);
cmd.Parameters.AddWithValue("#T_Address", modeledit.T_Address);
cmd.Parameters.AddWithValue("#Sub_Id", modeledit.Sub_Id);
cmd.ExecuteNonQuery();
conn.Close();enter code here
editlist.Add(modeledit);
}
return View(editlist);
}
This is My Html Code:
Index.cshtml:
#model IEnumerable<MvcApplication1.Models.Teacher>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
T_Id
</th>
<th>
T_Name
</th>
<th>
T_Address
</th>
<th>
Sub_Id
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.T_Id}) |
#Html.ActionLink("Details", "Details", new { id=item.T_Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.T_Id})
</td>
<td>
#item.T_Id
</td>
<td>
#item.T_Name
</td>
<td>
#item.T_Address
</td>
<td>
#item.Sub_Id
</td>
</tr>
}
**Edit.cshtml:**
#model MvcApplication1.Models.Teacher
#{
ViewBag.Title = "Edit";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Teacher</legend>
<div class="editor-label">
#Html.LabelFor(model => model.T_Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.T_Id)
#Html.ValidationMessageFor(model => model.T_Id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.T_Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.T_Name)
#Html.ValidationMessageFor(model => model.T_Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.T_Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.T_Address)
#Html.ValidationMessageFor(model => model.T_Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Sub_Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Sub_Id)
#Html.ValidationMessageFor(model => model.Sub_Id)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
Related
I have a partial view which does not show the data. Here is a simple version. Here are my Models. The parent and child records
namespace Partial.Models
{
using System;
using System.Collections.Generic;
public partial class Parent
{
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Parent()
{
this.Children = new HashSet<Child>();
}
public int ID { get; set; }
public string Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Child> Children { get; set; }
}
}
namespace Partial.Models
{
using System;
using System.Collections.Generic;
public partial class Child
{
public int ID { get; set; }
public Nullable<int> ParentID { get; set; }
public string Description { get; set; }
public virtual Parent Parent { get; set; }
}
}
Here are my controllers which only involve the index and edit forms.
namespace Partial.Controllers
{
public class ParentsController : Controller
{
private PartialEntities db = new PartialEntities();
// GET: Parents
public ActionResult Index()
{
return View(db.Parents.ToList());
}
namespace Partial.Controllers
{
public class ChildrenController : Controller
{
private PartialEntities db = new PartialEntities();
// GET: Children
public ActionResult Index()
{
var children = db.Children.Include(c => c.Parent);
return View(children.ToList());
}
Here is my view. Parent Form which is the edit form. Which should display the children index form
#model Partial.Models.Parent
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Parent</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<table class="table">
<tr>
<td>
Html.Partial("~/Views/Children/Index.cshtml", new List<Partial.Models.Child> ());
</td>
</tr>
</table>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Child Form which should display the children but doesn't
#model IEnumerable<Partial.Models.Child>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Parent.Description)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Parent.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
Please Try Code
Remove the code
Html.Partial("~/Views/Children/Index.cshtml", new List<Partial.Models.Child> ());
replace Code
#{Html.RenderAction("Index","Children");}
Sysntext For :
#Html.RenderAction("Action name","Controller name",Route values)
I want to be able to add players and upon addition in the same I want to display them in a table similar to what page Index view offers. so what I did is combine the index and create views in 1 page.
but when debugging I'm have a resource cannot be found error.
can some one please correct where I'm going wrong
Index View:
#model IEnumerable<sportsMania.player>
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>category</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.Label("Player Name")
<div class="col-md-10">
#Html.Editor("Player Name")
</div>
</div>
<div class="form-group">
#Html.Label("Team")
<div class="col-md-10">
#Html.DropDownList("team", ViewBag.team as SelectList)
</div>
</div>
<div class="form-group">
#Html.Label("Position")
<div class="col-md-10">
#Html.Editor("position")
</div>
</div>
<div class="form-group">
#Html.Label("Email")
<div class="col-md-10">
#Html.Editor("email")
</div>
</div>
<div class="form-group">
#Html.Label("Type")
<div class="col-md-10">
#Html.Editor("type")
</div>
</div>
<div class="form-group">
#Html.Label("Height")
<div class="col-md-10">
#Html.Editor("height")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.playerName)
</th>
<th>
#Html.DisplayNameFor(model => model.team)
</th>
<th>
#Html.DisplayNameFor(model => model.position)
</th>
<th>
#Html.DisplayNameFor(model => model.email)
</th>
<th>
#Html.DisplayNameFor(model => model.type)
</th>
<th>
#Html.DisplayNameFor(model => model.height)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.playerName)
</td>
<td>
#Html.DisplayFor(modelItem => item.team)
</td>
<td>
#Html.DisplayFor(modelItem => item.position)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
</td>
<td>
#Html.DisplayFor(modelItem => item.type)
</td>
<td>
#Html.DisplayFor(modelItem => item.height)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
playerController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace sportsMania.Controllers
{
public class playerController : Controller
{
sportsEntities db = new sportsEntities();
[HttpPost]
public ActionResult Index()
{
var data = from p in db.Teams
select p.teamName;
SelectList list = new SelectList(data);
ViewBag.team = list;
return View(db.players.ToList());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(player player)
{
if (ModelState.IsValid)
{
player newRecord = new player();
newRecord.playerName = Request.Form["Player Name"];
newRecord.position = Request.Form["position"];
newRecord.type =Request.Form[ "type"];
newRecord.team =Request.Form[ "team"];
newRecord.email = Request.Form["email"];
newRecord.height = Request.Form["height"];
db.players.Add(player);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(player);
}
}
}
why I am doing this? because I don't want every time the user have to add a Player he should be redirected to the create view, I want when user finishes adding players he will hit a button "done adding" and will be redirected home.
I am trying to display a complex viewmodel in a view, everything works fine except one dropdownlist. I am displaying a list of enum, and set the selected object as it should be. But for an unknown reason, its not showing the selected value. I have tried many times with but failed -- please help me. The code is given below -
Enum:
public enum CommentStatus
{
NoStatus = 0,
Resolved = 1,
NotApplicable = 2
}
Model:
public class CheckComments
{
public string EntryId { get; set; }
public int Serial { get; set; }
public string Comment { get; set; }
public DateTime CommentDate { get; set; }
public CommentStatus CommentStatus { get; set; }
}
public class CheckDataViewModel
{
public string EntryId { get; set; }
public string CheckId { get; set; }
public decimal Value { get; set; }
public List<CheckComments> CheckCommentsList { get; set; }
public List<string> CommentStatusList { get; set; }
}
Controller:
public class CheckDataController : Controller
{
public ActionResult GetEnteredCheckData(string entryId)
{
var checkDataViewModel = new CheckDataViewModel();
var checkData = new CheckDataManager().GetCheckData(entryId);
checkDataViewModel.EntryId = checkData.EntryId;
checkDataViewModel.CheckId = checkData.CheckId;
checkDataViewModel.Value = checkData.Value;
checkDataViewModel.CheckCommentsList = checkData.Comments;
checkDataViewModel.CommentStatusList = Enum.GetNames(typeof (CommentStatus)).ToList();
return View("EnteredCheckData", checkDataViewModel);
}
}
View:
#model PDCA.Web.Models.CheckDataViewModel
#{
ViewBag.Title = "EnteredCheckData";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.EntryId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.EntryId)
#Html.HiddenFor(model => model.EntryId)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Check Information</legend>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.CheckId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.Check.CheckId)
#Html.HiddenFor(model => model.Check.CheckId)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Comments</legend>
<div>
<table class="table table-bordered">
<tr>
<th>
Serial
</th>
<th>
Comment
</th>
<th>
Date
</th>
<th>
Status
</th>
<th>
</th>
</tr>
#for (int i = 0; i < Model.CheckCommentsList.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Serial)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Serial)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Comment)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Comment)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].CommentDate)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].CommentDate)
</td>
<td>
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus))
#Html.ValidationMessageFor(model => Model.CheckCommentsList[i].CommentStatus)
</td>
<td>
#Html.ActionLink("Update Status", "UpdateCommentStatus", new { Model.EntryId, Model.CheckCommentsList[i].Serial, Model.Check.CheckTitle, Model.Check.CheckId })|
#Html.ActionLink("Delete", "DeleteComment", new { Model.CheckCommentsList[i].Serial, Model.EntryId })
</td>
</tr>
}
</table>
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The code is too lengthy but I think this will help you to understand my mistakes. Thanks in advance friends.
Solution:
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus.ToString()))
I have used ComponentModel.DataAnnotations [Required] attribute for validation messages. The message is not getting displayed in my form. However, the RegularExpression validation and Range validation are working fine.
In one of my field, I used both [Required] and [RegualarExpression]. When I give the wrong input in the text box, the RegualarExpression validation message appears and after erasing the input, then only Required validation message. Otherwise, Required validation message does not appear.
Here is my code:
--Model Class
public class Email
{
[Required(ErrorMessage = "Email Address is required!")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9] {1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "Invalid Email Address.")]
public virtual string EmailAddress { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "First Name is Required")]
public virtual string FirstName { get; set; }
public virtual string MiddleName { get; set; }
[Required(ErrorMessage = "Last Name is required!")]
public virtual string LastName { get; set; }
public virtual string Status { get; set; }
}
--View
#{Html.EnableClientValidation();}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("CreateEmail", "LeaderBoard", FormMethod.Post, new { enctype = "multipart/form-data", id = "create-email-dialog" }))
{
#Html.ValidationSummary(true)
{
<form>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="popTable">
<tr>
<td width="38%">
First Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Middle Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.MiddleName)
#Html.ValidationMessageFor(model => model.MiddleName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Last Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Email Address:
</td>
<td width="62%">
<div class="errorMessage">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
</td>
</tr>
<tr>
<td width="38%">
Status:
</td>
<td width="62%">
<div class="editor-field">
#Html.DropDownList("Status", ViewData["Status"] as SelectList)
</div>
</td>
</tr>
</table>
<input type="button" id="btnCreateEmail" value="Save" name="submit" class="btn" />
<input type="button" value="Cancel" name="cancel" class="closeDialog" />
</form>
}
}
--Controller
[HttpGet]
public ActionResult CreateEmail()
{
if (Request.IsAjaxRequest())
{
var list = new SelectList(new[]
{
new{Id = "Active", Name = "Active"},
new{Id = "Inactive", Name = "Inactive"}
},
"Id", "Name", 1);
ViewData["Status"] = list;
return PartialView("_CreateEmail");
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult CreateEmail(Email model)
{
using (_emailRepository)
{
if (ModelState.IsValid)
{
_emailRepository.Create(model);
return Json(new { success = true });
}
return RedirectToAction("Index");
}
}
Validate those fields in the document ready function
$( document ).ready( function ( e )
{
$( "form" ).validate().element( "#FirstName" );
$( "form" ).validate().element( "#LastName" );
});
so what Iam trying to do is a view wiht both create and list in the same view, so I've read that I can usea ViewModel for this so I create my view model "EventoViewModel"
public class EventoViewModel
{
public Eventos Eventos { get; set; }
public IEnumerable<Eventos> LEventos { get; set; }
}
my controller:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Eventos eventos)
{
if (ModelState.IsValid)
{
db.Eventos.AddObject(eventos);
db.SaveChanges();
}
return RedirectToAction("Create");
}
My view: in the foreach part I get an ERROR, say nullreferenceException, what Iam doing wrong?
#model createList.Models.EventoViewModel
<h2>Create</h2>
#using (Html.BeginForm()) {
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Eventos.Nombre)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Eventos.Nombre)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<table>
<tr>
<th>
Nombre
</th>
</tr>
#foreach (var item in Model.LEventos) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nombre)
</td>
</tr>
}
</table>
I change my approach I use partial view now. and create a "List" partial view
Partial View: List
#model IEnumerable<createList.Models.Eventos>
<table>
<tr>
<th>
Nombre
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nombre)
</td>
</tr>
}
</table>
and in the end of my "create" view I call my "List" Partial view
#model createList.Models.Eventos
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Eventos</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Nombre)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Nombre)
#Html.ValidationMessageFor(model => model.Nombre)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
**#{Html.RenderAction("list", "Evento");}** // call de action "list"
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and my controllers:
public ViewResult List()
{
return View(db.Eventos.ToList()); //past a list of eventos
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Eventos eventos)
{
if (ModelState.IsValid)
{
db.Eventos.AddObject(eventos);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(eventos);
}