//Index Page (view) /Employee/Index
#model DataAnotaionExample.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
Enter Name=#Html.TextBoxFor(m=>Model.Name)
#Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
//Employee Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DataAnotaionExample.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
return View();
}enter code here
}
}
Model Class Employee.cs
namespace DataAnotaionExample.Models
{
public class Employee
{
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
This is my code, If I keep the Name field blank then it will not throw the error like the field is required.
This Code Created in Asp.Net MVC5 Framework
make sure you have added
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script
at the end of your layout page:
First you have add razor like this
#model DataAnotaionExample.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
//this one
#Html.ValidationSummary(true)
Enter Name=#Html.TextBoxFor(m=>Model.Name)
#Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
Then you should like validation script like this in your "_Layout.cshtml" page
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Or you can use this script in your App_Start->BundleConfig
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"
));
I hope this code is useful for you.
Related
I want to use following html tags in asp.net mvc,is it possible?
<form action="demo_form.asp">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
You just have to make your view as strong typed view using these code u get able to use this code.I hope this will help u.
C# Controller Code
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(sample b)
{
return View();
}
C# Class Code
public class sample
{
public string fname { get; set; }
public string lname { get; set; }
}
Razor View Code
#model WebApplication1.Models.sample
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#using (Html.BeginForm("index","Home"))
{
<input type="text" name="fname"><br>
<input type="text" name="lname"><br>
<input type="submit" value="Submit">
}
</body>
</html>
If you do not want to create a Strongly Typed View then you can just do like this.
[HttpPost]
public ActionResult Index(string fname, string lname)
{
return View();
}
I have created two models, Student and School and a composite model, StudentSchool. I am using two different partiel views to create one the Student and the other the School. However, in my controller, I am getting null values for both the Student and School. Below is my code:
Student:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LayoutProject.Models
{
public class Student
{
public int studentID { get; set; }
public String firstname { get; set; }
public String lastname { get; set; }
public int year { get; set; }
}
}
School:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LayoutProject.Models
{
public class School
{
public int schoolID { get; set; }
public String name { get; set; }
public String add { get; set; }
}
}
Composite model, StudentSchool:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LayoutProject.Models
{
public class StudentSchool
{
public Student student { get; set; }
public School school { get; set; }
}
}
PartielViewStudent:
#model LayoutProject.Models.Student
<h4>Student</h4>
#Html.LabelFor(d=>d.studentID) : #Html.TextBoxFor(d=>d.studentID)
<br />
#Html.LabelFor(d=>d.firstname) : #Html.TextBoxFor(d=>d.firstname)
<br />
#Html.LabelFor(d=>d.lastname) : #Html.TextBoxFor(d=>d.lastname)
<br />
#Html.LabelFor(d=>d.year) : #Html.TextBoxFor(d=>d.year)
<br />
PartialViewSchool:
#model LayoutProject.Models.School
<h4>School</h4>
#Html.LabelFor(d=>d.schoolID) : #Html.TextBoxFor(d=>d.schoolID)
<br />
#Html.LabelFor(d=>d.name) : #Html.TextBoxFor(d=>d.name)
<br />
#Html.LabelFor(d=>d.add) : #Html.TextBoxFor(d=>d.add)
<br />
The View:
#{
ViewBag.Title = "StudentSchool";
}
<h2>StudentSchool</h2>
<form action="/Home/CreateStudentSchools" method="post">
#using (Html.BeginForm())
{
#Html.Partial("_PartialViewStudent")
#Html.Partial("_PartialViewSchool")
}
<input id="createSD" type="submit" value="Submit"/>
</form>
The controller:
[HttpPost]
public ActionResult CreateStudentSchools(StudentSchool ss)
{
return View("CreateStudentSchool");
}
Any idea what I might be missing here? Been with this since 4 days.
Move you 'partial' views into the /Views/Shared/EditorTemplates folder and rename them to Student.cshtml and School.cshtml respectively (to match the names of the classes). Then in the main view use
#using (Html.BeginForm())
{
#Html.EditorFor(m => m.Student)
#Html.EditorFor(m => m.School)
}
The inputs your generating will now contain the correct name attribute for binding to your view model, for example name="Student.studentID" instead of the current name="studentID"
Note: As an alternative, you can pass the HtmlFieldPrefix to a Partial as indicated in this answer.
Its not a good idea if you provide the two partial views with different models and combining in one model.You have to pass the reference of the composite model to your partial views.
#using (Html.BeginForm())
{
#Html.Partial("_PartialViewStudent",Model.student)
#Html.Partial("_PartialViewSchool",Model.school)
}
This will work fine as with this approach as everything in the form is strictly typed.
In partial views also you have to specify models as
#model LayoutProject.Models.StudentSchool.student
#model LayoutProject.Models.StudentSchool.school
I am not sure about your [httpget] create method but it should be like
[HttpGet]
public ActionResult CreateStudentSchools(StudentSchool ss)
{
var studentsc=new StudentSchool()
{
student=new Student(),
school=new School()
}
return View("CreateStudentSchool",studentsc);
}
I've made a very simple mockup of my problem.
If i have a complex person viewModel:
public class PersonViewModel
{
public string Name { get; set; }
public List<DogViewModel> Dogs { get; set; }
}
public class DogViewModel
{
public string Name { get; set; }
}
And i have 2 views : to edit person and create a person :
#model Custom.Models.PersonEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit Person</h2>
<div class="PersonDataArea">
//this contain identical html in Create and Edit view
</div>
<div class="SelectDogAre">
//this contain identical html in Create and Edit view
</div>
<input type="button" value="save" />
#model Custom.Models.PersonCreateViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create Person</h2>
<div class="PersonDataArea">
//this contain identical html in Create and Edit view
</div>
<div class="SelectDogAre">
//this contain identical html in Create and Edit view
</div>
<input type="button" value="save"/>
And of course 2 ViewModels for each view :
public class PersonEditViewModel
{
public PersonViewModel Person { get; set; }
}
public class PersonCreateViewModel
{
public PersonViewModel Person { get; set; }
}
Question :
as you can see i have 2 identical areas in Create and Edit views, and i want to avoid to suplicate code. I cant use Partial views because model in partial view will not be bound on post. How to avoid duplication of the view code??
You definitely need to use a Partial View.
First of all, you don't need two separate View Models. Just the PersonViewModel is enough.
Then you'll create a partial view _PersonEdit.cshtml (by the way you are missing the form in your code):
#model Custom.Models.PersonViewModel
#using(Html.BeginForm())
{
<div class="PersonDataArea">
//this contain identical html in Create and Edit view
</div>
<div class="SelectDogAre">
//this contain identical html in Create and Edit view
</div>
<input type="button" value="save"/>
}
And, two Views for Create and Edit:
Create:
#{
ViewBag.Title = "Create";
}
<h2>Create Person</h2>
#Html.Partial("_PersonEdit", Model)
Edit:
#{
ViewBag.Title = "Edit";
}
<h2>Edit Person</h2>
#Html.Partial("_PersonEdit", Model)
Alternatively, you can create only one view for both actions, and pass the ViewBag.Title from the controller to the view.
I am not getting validation messages? Any idea how to resolve? please take a look at the view, the model, and the controller code below. I also attached the js files maybe im missing files?
#model MvcApplication1.Models.Assesment
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.name)
#Html.ValidationMessageFor(m=>m.name,"*Hello")
}
<input type="submit" value="submit" />
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class Assesment
{
[Required]
public string name { get; set; }
}
}
public class RegisterController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Assesment assesment)
{
return View();
}
}
Your <input type="submit"> should be inside the form.
Also, you should pass the invalid model to the view when handling the POST
[HttpPost]
public ActionResult Index(Assesment assesment)
{
return View(assesment);
}
By the way, a typical HttpPost action looks like this:
[HttpPost]
public ActionResult Index(Assesment assesment)
{
if( ModelState.IsValid )
{
// Handle POST data (write to DB, etc.)
//...
// Then redirect to a new page
return RedirectToAction( ... );
}
// show the same view again, this time with validation errors
return View(assesment);
}
Here is the scenario. I want to use CKEditor for a rich text field on a form, but for whatever reason I cannot get the contents from the textarea to the server and back to the page without encoding problems. Here is the little sample program I wrote up to try and figure out what is going on. First, my view model:
HomeViewModel.cs
namespace CkEditorTest.Models
{
public class HomeViewModel
{
[Required]
[DataType(DataType.Html)]
[Display(Name = "Note")]
public string Note { get; set; }
}
}
Now my controller:
HomeController.cs
using System.Web.Mvc;
using CkEditorTest.Models;
namespace CkEditorTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new HomeViewModel());
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(HomeViewModel model)
{
return View(model);
}
}
}
And finally, my view:
Index.cshtml
#model CkEditorTest.Models.HomeViewModel
#{
ViewBag.Title = "CKEditor Test";
}
#section head
{
<script type="text/javascript" src="#Url.Content("~/Scripts/ckeditor/ckeditor.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/ckeditor/adapters/jquery.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Note").ckeditor();
});
</script>
}
<h2>CKEditor Test</h2>
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Note)<br /><br />
#Html.TextAreaFor(m => m.Note)<br />
<input type="submit" />
}
#if (!String.IsNullOrEmpty(Model.Note))
{
<div id="noteText">#Model.Note</div>
}
No matter what I do, I cannot display the Model.Note property as html on my view. By the time it reaches the view it is HTML encoded (i.e. <p> etc...). Here is what the form looks like pre-post:
pre-post http://www.matthewkimber.com/images/so/pre-post.png
And here is what the result is in the div below the "Submit" button:
post result http://www.matthewkimber.com/images/so/posted.png
I've set a breakpoint within Visual Studio and it shows as bare angle brackets (no encoding on HTML elements, just characters).
breakpoint results http://www.matthewkimber.com/images/so/dataInsideTheActionMethod.png
This, of course, is the stripped down test. I've tried encoding it, decoding it both in the view and in the controller to no avail.
By default everything is encoded when you use razor. I think you're looking for the Raw method.
It would also be a good idea to check the response using Fiddler or Firebug.
Try this:
#Html.DisplayTextFor(modelItem => item.Note)
You can also use HtmlString("")