Category Archives: TextBox

TextBox

[RESOLVED]Issue with Razor and VB.net Supplying a default value

I have been able to do this with C# but with VB.net in the view I am having issues with syntax.

C# works great:
@Html.TextBoxFor(model => model.Address, new { @class="BTCaddress", @Value="" + ViewBag.Address + "" })

Not sure how to format in VB.net? I also have issues getting it to work with EditorFor:

Regular scaffolded code:
@Html.EditorFor(Function(model) model.Company, New With {.htmlAttributes = New With {.class = "form-control"}})

What I have tried:
@Html.EditorFor(Function(model) model.Company, New With {.htmlAttributes = New With {.class = "form-control", @Value="" & @ViewBag.Company & "" }})

Should I be using TextboxFor  in VB.net for this and how would I format it?

Hi,

Based on my test in the MVC 5 project, I found that we can’t set the default value by specify the data to the value.

For the Html.XXFor method, the default value should be based on the field value of Model. So, you need to create an instance with the default value and return to the view. You also could use
Html.TextBox method.

belcherman

@Html.TextBoxFor(model => model.Address, new { @class="BTCaddress", @Value="" + ViewBag.Address + "" })

Not sure how to format in VB.net? I also have issues getting it to work with EditorFor:

The VB code should be:

@Html.TextBoxFor(Function(m) m.Address, New With {.class = "BTCaddress",.value=ViewBag.Address})

Best Regards

Starain Chen

[RESOLVED]MVC 4 generate ViewModel from multiple tables

I want to generate ViewModel (contains Teacher Name and list of student’s Names) from multiple tables. Teachers table and Student table.

   Teacher’s model contains  public virtual ICollection<Student> Students { get; set; }

var model = (from x in db.Teachers where x.Email = email select new TeacherVM { Name = x.Name, StudentNames = x.Student.ToList() }).FirstOrDefault()

How do I retrieve all students into the TeacherVM in a format ("Bob","Mike","Dan")

Thanks,

Can you post your Teacher and Student models?

 public class Teachers
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Student> Students { get; set; }
      …..
   }

    public class Student
    {
        public int Id { get; set; }
        public string Name{ get; set; }
        public virtual ICollection<Teachers> Teachers{ get; set; }
        …..
    }

And you want to list all students assigned to a specific teacher?  Or you just want to list all teachers and all students?

all students assigned to a specific teacher

so the viewmodel would contain 2 fields Teacher Name and list of all students

I tried this but I think I am missing something.

var model = (from x in db.Teachers where x.Email = email select new TeacherVM { Name = x.Name, StudentNames = x.Student.ToList() }).FirstOrDefault()

In the view I want to display 2 textboxes first textbox "Teacher Name" and another textbox all students comma separated
Bob,Mike,Dan

Thanks,

Do you have a relationship mapping between Teacher and Student?  Typically when you have a many-to-many relationship schema, you need a 3rd class/model/table that maps the relationship between those tables.  With your current two tables, you don’t have any
way of knowing which student belongs to which teacher, and vice versa.

Example:

public class Enrollment
{
  public int EnrollmentID { get; set; }
  public int TeacherID { get; set; }
  public int StudentID { get; set; }
}

and then you’d need primary keys in your Teacher and Student tables:

    public class Teachers
    {
        public int TeacherID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
      .....
    }

    public class Student
    {
        public int StudentID { get; set; }
        public string Name{ get; set; }
        public virtual ICollection<Enrollment> Enrollments{ get; set; }
        .....
    }

Your Enrollments table would then have data like this:

EnrollmentID TeacherID StudentID
1 1 2
2 1 3
3 2 1
4 2 3

As you can see in the table above, Teacher #1 has Students #2 and #3, while Teacher #2 has Students #1 and #3.  Student #3 has teachers #1 and #2.  This is critical information that we need to have for many-to-many relationships.

Once you have this schema, you can create your Teacher-Students list

Teacher Details action:

public ActionResult TeacherDetails(int id)
{
  var teacher = db.Teachers.Find(id);

  return View(teacher);
}

View:

@model AppName.Models.Teacher

Teacher Name: @Model.Name
Teacher Email: @Model.Email

<h3>Students assigned to Teacher</h3>

@foreach (var item in Model.Enrollments)
{
  @Html.DisplayFor(modelItem => item.Student.Name) <br />
}

And that’s it.  Pretty standard solution for many-to-many relationships.

Thanks John for the explanation all makes sense. I was wondering instead of 

  var teacher = db.Teachers.Find(id);

to add teacher’s record and the student names into viewmodel in the controller

 public class TeacherVM 
    {
       public string Name { get; set; }
       public string StudentNames { get; set; } 
    }

something like this:

var model = (from x in db.Teachers 
             where x.Email = email 
             select new TeacherVM { 
                Name = x.Name,
                StudentNames = ??  <-- not sure how to get the list
             }).FirstOrDefault()
return View("teacher", model)

and then pass the viewmodel into the view so instead of doing a foreach to retrieve each single student.name I would just pass a string that would contain 
Bob,Mike,Dan into the textbox so the that the teacher can update the textbox right away instead of having edit button and another page. I hope it makes sense what I want to do. thanks for your help!

Sorry for the delayed response.  Let’s take a look at why you can’t do it the way you want to.

Yes, you could totally use a view model if you wanted, however you still need a relationship mapping between teacher(s) and student(s).  This is why I suggested a 3rd table (Enrollments) to establish which student has which teacher, and vice versa.

StudentNames = ??  <-- not sure how to get the list

With your current solution (Teacher and Student tables only), you have no way of getting this list.  There’s no association between the two.  Hence, you need that Enrollments table.  If you had that table, you could do something like this:

var teacher = db.Teachers.Single(t => t.Email == email);
var students = db.Students.Where(s => s.Enrollments.TeacherID == teacher.TeacherID); var model = new TeacherVM(); model.Name = teacher.Name; model.StudentNames = string.Join(",", students); return View(model);

As you can see, we use the Enrollments model to track down the students that have the teacher’s ID associated to their record in the Enrollments table.  How ever you want to handle this solution, you need to have a table that manages your many-to-many relationships.

You are absolutely correct. Sorry it took me a while to get this, new to mvc. But you made it all clear. Appreciate your help.

[RESOLVED]Asp.net MVC Controller / Model Quandry

Consider the following two Models: AModel
(Class A)
 and BModel
(Class B)
, and two partial views:AView
(bound to AModel)
 and BView
(bound to BModel)
.

I have a Controller called TestController.
In TestController I
have the following methods:

<HttpPost>
Function Index(model as AModel) As ActionResult
    Return View(model)
End Function

<HttpPost>
Function Index(model as BModel) As ActionResult
    Return View(model)
End Function

In Index I
have the following code:

@Using Html.BeginForm()
@<div>
    @Html.Partial("~/Views/Test/AView.vbhtml")  ' this is here for test only
    <div><input type="submit" name="submit" value="Submit" /></div>
</div>
End Using

My partial views look like this:

@ModelType Company.Domain.Models.ModelA '(or ModelB for the other)

<div>@Html.LabelFor(Function(m) m.Name)</div>
<div>@Html.TextBoxFor(Function(m) m.Name)</div>

... and so on, several Input fields follow ...

When I fill in and submit AView I get the following error:

The current request for action 'Index' on controller type 'TestController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(Company.Domain.Models.AModel) on type Company.WebUI.Controllers.TestController
System.Web.Mvc.ActionResult Index(Company.Domain.Models.BModel) on type Company.WebUI.Controllers.TestController

After some research I tried putting <ActionName("Index")> over
each Index method in TestController but
generates the same error (I changed the method names to AIndex and BIndexthen
placed the action name attribute above them and tested
.)

What I’m trying to achieve: I have two forms I need my user to fill out (one after the other). Each form has it’s own set of properties and validation (naturally), hence AModel and BModel. I created two matching Partial Views (partial because I
will want to use those views within other main views later on).

I’m lost as to how to achieve what I want here because ASP.NET isn’t recognizing the different method signatures, nor am I sure I’m going about doing this correctly under ASP.NET MVC anyway. Under a competing platform I would simply #INCLUDE my
pages as needed.

I hope my explanation is clear, appreciate any advice.

put the names of the 2 actions as IndexA and IndexB

Html.BeginForm supports adding action name

ASP.NET MVC Controllers do not support overloading Controller Actions (e.g. you cannot have two Actions with the same name that expect the same type of request like POST).

Using an ActionName attribute

You really have two options here. You could explitly change the name of each of your actions :

<HttpPost>
Function A(model as AModel) As ActionResult
    Return View("Index",model)
End Function

<HttpPost>
Function B(model as BModel) As ActionResult
    Return View("Index",model)
End Function

Or you can explicitly set a name for the action using an [ActionName] attribute :

<HttpPost>
<ActionName("A")>
Function Index(model as AModel) As ActionResult
    Return View("Index",model)
End Function

<HttpPost>
<ActionName("B")>
Function Index(model as BModel) As ActionResult
    Return View("Index",model)
End Function

You obviously don’t need to assign an ActionName to both of them, but at least one will need it in order differentiate between the two.

Ensuring Proper Posting

Another issue here is that ASP.NET MVC is not going to know which particular Action that you are trying to POST to from your form unless you explicitly specify it within the BeginForm() Helper method :

@Using Html.BeginForm("A","Test")
@<div>
    @Html.Partial("~/Views/Test/AView.vbhtml")  ' this is here for test only
    <div><input type="submit" name="submit" value="Submit" /></div>
</div>
End Using

If you use the ActionName attributes mentioned above (or simply rename the Action), this should now refer to the "A" method and will POST your "A" Model to the appropriate action. If you are going to be setting some of these values dynamically (such
as an AJAX call
), then you’ll likely want to include the <form> itself within the Partial Views to avoid any confusion of where to POST to.

[RESOLVED]Pop Up not posting data to controller

Hi! I am pretty new to ASP.NET MVC5, and I am dealingwith something strange,

I have a view , displaying some data from the model that the controller returns (a, b, c), and threeHidden fields with those values.

@using (Ajax.BeginForm("Registro", "Experiencias", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "detalleSuccess" }, new { id = "DetalleForm", name="DetalleForm" }))
{
    
    @Html.Hidden("idExperiencia", Model.a)
    @Html.Hidden("exclusiva", Model.b)
    @Html.Hidden("idPregunta", Model.c)
    <div class="texto">
         <h2 class="titulo">@Model.a</h2>
         <p class="font_18">@Model.b</p>
         <p class="font_18">@Model.c</p>
    </div>
    <div class="row_derecha">
       <a href="#" class="boton_azul pos_abajo basic6" onclick="ParticiparModal('modal-popup')">Show</a>
    </div>


    <div id="modal-popup" style="display: none;">
         <div class="campo_datos ">
              @Html.TextBoxFor(model => Model.email, new { @class = "input_popup", id = "email", name="correoElectronico"})
         </div>
         <div class="container_boton_condiciones submitbutton" data-form-name="DetalleForm"><a class="boton_grande naranja" href="#">Send</a></div>
    </div>

In the view there is a link that opens the pop up "modal-popup". This pop up has a text box where the user must enter an email address and it is supoosed to be stored in the model.email field. Then if you click in the Send button, the form is submitted.

The problem is that the POST controller action receives a Model object but it is allways null, I think it’s because the model is quite complicated, it has a list inside it and some other objects, and the model binder does not know how to translate it, so
I want to do a Model Binder.

To do it I look at the POST action that is sent by the form (with firebug)  and I see that in the POST action it only sends the hidden fields that are outside of the pop up, in this case it only sends "idExperiencia", "exclusiva" and "idPregunta", I have
tried to add a hidden field in the pop up but it doesn’t appear in the post parameters.

Do you have any idea why the post action is only sending the hidden fields of the main page?

I hope somebody could help me

Thanks!

Post your entire view and model please

you don’t say which modal framework you are using, but most move the modal content to end of the body to make the css work. of course after this, the field is no longer in the form. you need to put the form in the modal, or write javascript to move the modal
back (may need to modify css to get this to work).

 

[RESOLVED]How to import Resume in Asp.net MVC

I want to import a resume like when a resume is uploaded, immediately resume content like candidate skills,experience should display on text fields like skills on skills textbox from resume, experience in experience textbox from resume. How it is possible,
can u give me some example how to do this in Asp.net mvc.

Is there any .dll to do that?

I have tried on google, but i didn’t get perfect example, please help anyone

Sanjay_Net

. How it is possible, can u give me some example how to do this in Asp.net mvc.

MVC does not read Word documents. You should try some other controls, such as ASPOSE

In addition to aspose you can try DocX (http://docx.codeplex.com/) or the XML SDK.

Reading the Word document itself is only half the issue, the other is parsing it intelligently to extract the data you need, which is not a trivial process.  People build whole businesses around what you’re trying to do, it’s unlikely you’re going to get
someone to give you industry leading code for free.  I’m sure there will be components that do this work already if you google for them.

There are some third party tools that provides the resume parsing functionality. Please take a look at these sites

http://www.sovren.com/sovren-resume-cv-parser/

http://rchilli.com/solutions/b2b-web-api/

If you don’t want to go with third party tools, then I recommend to take a look at Open XML toolkit.

http://msdn.microsoft.com/en-us/library/office/bb448854(v=office.15).aspx

Can you give some reference example using Open XML toolkit, that how it will work.

I googled "open xml sdk read word document" and here are some links, if you google yourself you’ll find a lot more

http://msdn.microsoft.com/EN-US/library/office/cc850833(v=office.15).aspx

http://justgeeks.blogspot.co.uk/2011/09/reading-ms-word-2007-document-in-docx.html

[RESOLVED]How to validate specific textbox fields using asp.net mvc 4

Hello all,

I have created a simple asp.net MVC form. I have five fields and one radio button list having values Yes and No on this form.

When i click on radio button Yes value i want to validate first three fields, but when i click on No i want to validate other two fields but not the first three. How can i achieve this according to above scenario?

Thanks.

Hi there

You can do this by creating a customised Validate method in your model class. Remember to make your model class implement IValidateObject.

public class MyModel : IValidatableObject
{
    public bool YesOrNo { get; set; }
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
    public string Value4 { get; set; }
    public string Value5 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {
        if (YesOrNo)
        {
             // Validate first 3 fields

             // If, for example, Value1 fails, use this line:
             yield return new ValidationResult("Error!", , new[] { "Value1" });
        }
        else
        {
            // Validate  other 2 fields

            // If Value 4 fails, use this line:
            yield return new ValidationResult("Error!", new[] { "Value4" });
        }
    }
}

Let me know if you need more details.

Write following code on radio button click.

$("#formID").valid();

This will validate all the controls inside form.

Thanks for the reply,
I have some confusion in ur code. First of all please explain following line of code word by word:
public IEnumerable<ValidationResult> Validate(ValidationContext context)

Secondly I have to validate on button click so how can I fit ur code on button click, thanks.

That line is just a declaration for a method on your model class. It returns a collection of ValidationResults to the ModelState in your controller. The ValidationContext that is passed in happens automatically. Because you’re implementing the IValidateObject
interface you need that signature but in this case you don’t need the context so just ignore it. 

As for making it validate on button click, well that means you either want to forget my suggestion and just validate with Javascript, or if you want it to validate server side (on post back) then just add a submit button and ensure your form action matches
the action in your MVC controller. 

Hi Rauf,

For these requirement, you could use MVC Foolproof Validation (RequiredIF etc…).

More information, please refer to:

# MVC Foolproof Validation

http://foolproof.codeplex.com/

You also could custom validation to achieve that.

About custom validation, please refer to:

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Best Regards

Starain Chen

For this scenario , I Jquery validation is the best solution

Jquery validation :

$(document).ready(function () {
var isChecked = jQuery("input[name=radiobtnYes]:checked").val();
     if(!isChecked){
         /// Check validation for No
     }else{
         /// Check validation for Yes
     }
}); 
Thanks for ur reply,
Your idea look good to me. But for example if I have 20 textboxes then shall I have to write validation rule for every texbox? Is there not any other way or out of the box way like mvc unobstrusive validation in which we just write [required] in model class
and everything done! I just want that i should not write many lines for every textbox for validation, thanks.

Hi Rauf,

After you custom the validation, you could use it to those fields/properties, it is the same as
required. So, you don’t need have multiple validation for these fields/properties.

Best Regards

Starain Chen

Really your requirement of conditional validation means you’re going to need some customized code. Your options are:

Customized Validate method (as per my first post)

Customized Attribute

Javascript

Another javascript option is jquery validate (http://jqueryvalidation.org/)

I recommend this as something you should look into anyway, it’s not hugely complicated and allows you to do the kind of customized validation you’re trying to do quite easily, without needing to know too much javascript (you just need to read through the
documentation). You can use it in lots of projects!

You can set "depends" on your options to a jquery function which checks if they should be validated. There’s an example here:

https://stackoverflow.com/questions/379838/using-depends-with-the-jquery-validation-plugin

[RESOLVED]Always filtering Index View on Bool Entity / Displaying only a subset of data

I would like to have the index view (code below) always filter the data on a bool entitiy so that only a subset of the database displays – not the entire database.

If anyone could point me in the right direction, I would appreciate it.

Index.cshtml

@model PagedList.IPagedList<GenericWebApplication.Models.Class_EntitySet01>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Class_EntitySet01";
}

<h2>Class_EntitySet01</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm("Index", "Class_EntitySet01", FormMethod.Get))
{
    <p>
        Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
    </p>
}

<table>
    <tr>
        <th>
            @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th>
            First Name
        </th>
        <th>
            @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th></th>
    </tr>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity01)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity02)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity21)
        </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>

<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Class_EntitySet01Controller.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GenericWebApplication.Models;
using GenericWebApplication.DAL;
using PagedList;
using System.Data.Entity.Infrastructure;

namespace GenericWebApplication.Controllers
{
    public class Class_EntitySet01Controller : Controller
    {
        private GenericWebApplicationContext db = new GenericWebApplicationContext();

        // GET: /Class_EntitySet01/
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;           
            
            
            var class_entityset01s = from s in db.Class_EntitySet01s
                           select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                class_entityset01s = class_entityset01s.Where(s => s.Property_Entity01.ToUpper().Contains(searchString.ToUpper())
                                       || s.Property_Entity02.ToUpper().Contains(searchString.ToUpper()));
            }
            
            switch (sortOrder)
            {
                case "name_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity01);
                    break;
                case "Date":
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity21);
                    break;
                case "date_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity21);
                    break;
                default:
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity01);
                    break;
            }

            int pageSize = 3;
            int pageNumber = (page ?? 1);

            return View(class_entityset01s.ToPagedList(pageNumber, pageSize));
        }

        // GET: /Class_EntitySet01/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Class_EntitySet01/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Class_EntitySet01s.Add(class_entityset01);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(class_entityset01).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Delete/5
        public ActionResult Delete(int? id, bool? saveChangesError = false)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            try
            {
                Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
                db.Class_EntitySet01s.Remove(class_entityset01);
                db.SaveChanges();
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                return RedirectToAction("Delete", new { id = id, saveChangesError = true });
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

__________________________________________________________________

Programming Environment:

    Visual Studio 2013
    .NET 4.5
    Entity Framework 6 (EntityFramework 6.1.0 NuGet package)
    OS: Windows 7

Project Based On:
Getting Started with Entity Framework 6 Code First using MVC 5

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

var class_entityset01s = from s in db.Class_EntitySet01s
                           where s.SomeField == true
                           select s;

Thank you SO much!

[RESOLVED]Something is triggering unobtrusive validation, but what?

I have a fairly simple mvc form with validation.  One of the sections is a dynamically added partial view (add a new row with a button click).  Something in there is triggering a validation error, but I can’t find it.  It is requiring the IdentificationType
dropdown have a selected value, but as far as I can see, there is no "Required" set anywhere in the code.  There are 4 different sections setup as dynamiclly added partials and they are all fine.  The only difference I can see is the id type is a dropdown,
and it is the only one triggering the validation error.  Is this a dropdown thing?  Here is some code:

Partial view:

        <div class="IdentPartial" > 
             <div class="formGroup-Short">
                <div class="editor-label">
                    @*@Html.HiddenFor(m => m.IdentificationCounter, new { @class="iHidden" })*@
                    @Html.Label("Identification Type")
                </div>
                <div class="editor-field">
                     @Html.DropDownListFor(m => m.IdentificationModel[Model.IdentificationCounter].IdentificationType, new SelectList(Model.IDTypes, "Value", "Text"), "Select", new { style = "width: 150px;" })
                </div>
            </div>
        
            <div class="formGroup-Short">
                <div class="editor-label">
                    @Html.Label("Identification Number")
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.IdentificationModel[Model.IdentificationCounter].IdentificationNumber, new { style = "width:120px" })
                </div>
            </div>

            <div class="formGroup">
                <div class="editor-label"  style="width: 100px">
                    @Html.Label("Issuing State")
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(m => m.IdentificationModel[Model.IdentificationCounter].IssuingState, new SelectList(Model.State, "Value", "Text", "OR"), "Select", new { style = "width: 65px; margin-right:20px;" })
                </div>
            </div>
        </div>

ID Model:

    public class IdentificationMetadata
    {

        [DisplayName("Identification Type")]
        public string IdentificationType { get; set; }

        [DisplayName("Identification Number")]
        public string IdentificationNumber { get; set; }
        
        [DisplayName("State")]
        public string IssuingState { get; set; }
    }

jQuery script, button event:

            $("#AddId").on("click", function () {
                var itemIndex = $(".IdentPartial .iHidden").length;
                $.get(
                    "@Url.Action("NewIdentRow")/" + itemIndex,
                    function (data) {
                        $("#IdentDataSection").append(data);
                    });
            });

Can you send the exact error message you are getting it?

As far as i see you don’t have a required field in your model.

I finally found the solution, the IdentificationType was a not null int in the DB.  I made it nullable in the DB and changed it int he model, now if doesnt trigger the validation.

[RESOLVED]Viewmodel validation in asp.net mvc

Hi,

I have an asp.net mvc form. The form uses jquery to post the data and a viewmodel is bind to it. To validate the form, I am using the in-built data annotation attributes. But this does not seem to work with a view model. Please help me here. Below is my
sample code for the view and viewmodel.

Thanks.

@using (Html.BeginForm("AddProject", "Project", FormMethod.Post))
{ 
    @Html.ValidationSummary(true)
    
    <table cellspacing="5" cellpadding="10">
<tr>
<td>@Html.HiddenFor(model => model.ProjectID)</td>
</tr> <tr> <td>Project Year:</td> <td>@Html.DisplayFor(model => model.ProjectYear)</td> </tr> <tr> <td>Project Name:</td> <td> @Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name) </td> </tr> <tr> <td>Description:</td> <td>
@Html.TextAreaFor(model => model.Description, 5, 30, new { style = "spellcheck: false;" })
@Html.ValidationMessageFor(model => model.Description)
</td> </tr> <tr> <td><input type="button" value="Submit" onclick="SubmitForm();" /></td> </tr> </table> }

Viewmodel

namespace ProjectStatus.ViewModels
{
    public class ProjectViewModel
    {
        private ProjectEntities db = new ProjectEntities();

        public int ProjectID { get; set; }
[Required] public string Name { get; set; }
[Required] public string Description { get; set; }
public short ProjectYear { get; set; }
public ProjectViewModel() { } public ProjectViewModel(Projects prj) { ProjectID = prj.ProjectID; Name = prj.Name; Description = prj.Description; ProjectYear = prj.ProjectYear; } } }

Try this:

 @Html.ValidationSummary(false)

Note you can also try @Html.ValidationSummary

You should also be able to put a break point in the controller method to see what values are being returned.

@v2kea60

I tried it, but that does not seem to solve the issue.

Please include the below 2 scripts and reference it in your view.

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Hi User220,

According to your description, I would like to know how do you use JQuery to post data.

First, please refer to asif’s reply.

Secondly, if you are using the AJAX to submit the data, please call valid() method to do validate.

$("Form").valid();

Best Regards

Starain Chen

[RESOLVED]Ajax.BeginForm() and validaiton message?

How to display the validation message of the Model while using Ajax.BeginForm() ?

It does not matter between Html.BeginForm and Ajax.BeginForm. while declaring validation

1) Please add validation message in Model class as in Html.BeginForm validation

2) Then specify modal dialog name as UpdateTargetId in Ajax.BeginForm

Ajax.BeginForm("Action", "Controller", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "modal-dialog-name"})

If you are loading controls after the Ajax post and want to enable the validations after the post, you need to manually invoke the validator as shown below

$.validator.unobtrusive.parse('form');

Here is the code I used earlier for this

Ajax.BeginForm(new AjaxOptions() { UpdateTargetId = "AjaxViewContainer", OnSuccess = "RegisterAjaxEvents();", LoadingElementId = "LoadingDiv" });

JavaScript

function RegisterAjaxEvents() {
    $.validator.unobtrusive.parse('form');
    //remaining code
}

Hi abhi0410,

Thanks for your post.

First You enabled validation in the web.config page:

<add key="ClientValidationEnabled" value="true" />   
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

And you can follow these steps:

Unobtrusive AJAX Form Validation in ASP.NET MVC

http://www.codeproject.com/Articles/460893/Unobtrusive-AJAX-Form-Validation-in-ASP-NET-MVC

More information:

Ajax.BeginForm and validation

Ajax.BeginForm not working with Html.ValidationSummary

If there’s anything else I can do for you regarding this matter, please feel free to post it in this forum.

Best Regards,

Eileen

Hello
pprasannak,

i tried but your solution little different.

I have partial view with save button but on first click my server validation occurs.

And when i click second time then i get those error message in my view.

My partial view is loaded dynamically in a view based on click of button present in the view.

<script type="text/javascript">
    function RegisterAjaxEvents() {
        $.validator.unobtrusive.parse('form');
    }
</script>

@using (Ajax.BeginForm("Add", "Account", new AjaxOptions() { UpdateTargetId = "messageid", HttpMethod = "Post", OnSuccess = "RegisterAjaxEvents();" , InsertionMode=InsertionMode.Replace}))
{
    @Html.AntiForgeryToken()
    <div>
        @Html.ValidationSummary(true)
        <table>
            <tr>
                <td>
                    @Html.LabelFor(model => model.name, new { @class = "label" })
                </td>
                <td>
                    @Html.TextBoxFor(m => m.name, new { @class = "textbox" })
                    @Html.ValidationMessageFor(model => model.name, string.Empty, new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>
                      @Html.LabelFor(model => model.Userid, new { @class = "label" })
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Userid, new { @class = "textbox" })
                    @Html.ValidationMessageFor(model => model.Userid, string.Empty, new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.Email, new { @class = "label" })
                </td>
                <td>
                    @Html.TextBoxFor(model => model.Email, new { @class = "textbox" })
                    @Html.ValidationMessageFor(model => model.Email, string.Empty, new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>
                    
                </td>
                <td>
                    <div id="messageid"></div>
                    <div>
                        <input type="submit" value="Save" class="btn btn-default" />
                    </div>
                </td>
            </tr>
        </table>
    </div>
}

Hi
Eileen ni

Can you please look into my code snippet and guide me why the validation fires on second click and not in first click?

Thanks

abhi0410

OnSuccess = "RegisterAjaxEvents();"

The validation is firing second time because you are explicitly calling the RegisterAjaxEvents function on the success of the first button click.

For some reason your initial loading is not registering the validator. As a work around try this

<script type="text/javascript">
    function RegisterAjaxEvents() {
        $.validator.unobtrusive.parse('form');
    }

  RegisterAjaxEvents() // call the function manually
</script>

Also move this javascript to the end of the page (after end of the BeginForm)

Hi
pprasannak
,

Thanks.

It works by calling explicitly. but what could be the reason that validator is not registered in initial loading?

And how to highlight the textbox for which the error has occurred?

Ok i could add validation color to the textbox by simply passing the below css pattern to my css file

.input-validation-error
{
    border: 1px solid #ff0000;
    background-color: #ffeeee;
}

Rest was taken care by jquery.