0
votes

I am new to MVC and i am working on MVC 4 with razor and i made an employee page with model class and entity framework as :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace learnMVC.Models
{
public class EmployeeData
{
    [Required(ErrorMessage = "Please enter your Employee ID")]
    public int employeeID
    { get; set; }

    [Required(ErrorMessage = "Please enter your Name")]
    public string employeeName
    { get; set; }

    [Required(ErrorMessage = "Please enter your Date Of Birth")]
    public DateTime dateOfBirth
    { get; set; }

    [Required(ErrorMessage = "Please enter your Date of Joining")]
    public DateTime dateOfJoining
    { get; set; }

    [Required(ErrorMessage = "Please enter your Supervisor")]
    public string supervisor
    { get; set; }
}
}

This is my home controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using learnMVC.Models;

namespace learnMVC.Controllers
{
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        var empList = new List<EmployeeData>();
        //string constr = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        //SqlConnection connection = new SqlConnection(constr);
        //connection.Open();
        //SqlCommand command = new SqlCommand("Select * from  [Table]", connection);
        //SqlDataReader reader = command.ExecuteReader();
        //while (reader != null)
        //{
        //    EmployeeData obj = new EmployeeData();
        //    obj.employeeID = Convert.ToInt32(reader["Employee ID"]);
        //    obj.employeeName = (reader["Employee Name"]).ToString();
        //    obj.dateOfBirth = Convert.ToDateTime(reader["Date Of Birth"]);
        //    obj.dateOfJoining = Convert.ToDateTime(reader["Date Of Joining"]);
        //    empList.Add(obj);
        //}

        EmployeeData tempvar = new EmployeeData();
        tempvar.employeeID = 40;
        tempvar.employeeName = "Amit";
        tempvar.dateOfBirth = (Convert.ToDateTime("02-02-2012")).Date;
        tempvar.dateOfJoining = (Convert.ToDateTime("02-02-2012")).Date;
        tempvar.supervisor = "Head";
        empList.Add(tempvar);

        ViewData["EmployeeList"] = empList;
        //ViewBag["EmployeeList"]
        return View("Index");
    }

    //
    // GET: /Home/Create
    public PartialViewResult Insert()
    {
        if (Request.IsAjaxRequest())
        {
            return PartialView("Insert", new EmployeeData());
        }

        return PartialView("Insert");
    }

And this is my index.cshtml is :

@model IEnumerable<learnMVC.Models.EmployeeData>
@using learnMVC.Models

@{
ViewBag.Title = "Index";
}

<h2 style="margin-left:40%">Index</h2>

<script lang="javascript" type="text/javascript"      src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<script>
function showView(resultView) {
    alert("hello");
    $("#ReplaceSection").dialog({          //resultView
        modal: true,
        width: "auto",
        height: "auto",
        position: "center",
        resizable: false,
        closeOnEscape: true,
        open: function (ev, ui) {
        }
    });
}
</script>


@using (Ajax.BeginForm("IndexForm", new AjaxOptions { HttpMethod = "GET" }))
{
@Html.ValidationSummary()
<div id="indexDivision" style="margin-left:25%">
        <table class="Grid" cellspacing="20">
            <tr>
                <th>Employee ID</th>
                <th>Employee Name</th>
                <th>Date Of Birth</th>
                <th>Date Of Joining</th>
                <th>Supervisor</th>
                <th  colspan="2"></th>          
           </tr>

          @foreach (var p in (List<EmployeeData>)ViewData["EmployeeList"])
          {
            <tr>
                <td>@p.employeeID</td>
                <td>@p.employeeName</td>
                <td>@p.dateOfBirth</td>
                <td>@p.dateOfJoining</td>
                <td>@p.supervisor</td>
                <td>@Html.ActionLink("Edit", "Edit")</td>
                <td>@Html.ActionLink("Delete", "Delete")</td>
           </tr>
          }              
        </table>

    <div id="ReplaceSection">

    </div>

        @*@Html.ActionLink("Create New Record", "Insert")*@
        @Ajax.ActionLink("Create New Record", "Insert", 
        new AjaxOptions { HttpMethod = "GET", 
             InsertionMode = InsertionMode.Replace, 
             UpdateTargetId = "ReplaceSection", 
             OnComplete = "showView();",
             Confirm="Want to save this new record?"})

</div>

}

And my Insert partial view is as such :

@model learnMVC.Models.EmployeNewDBEntities

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

@using (Ajax.BeginForm(@using (Ajax.BeginForm("InsertForm", new AjaxOptions { HttpMethod = "GET" }))

) { @Html.ValidationSummary(true)

<fieldset>
    <legend>EmployeNewDBEntities</legend>

    <h1 style="margin-left:30%; width: 350px;">Insert New Record</h1>

        <div id="InsertDvivision" style="margin-left:30%; width: 350px;">
            <p>Employee ID :      @Html.TextBox("insertEmployeeID")</p>
            <p>Name :             @Html.TextBox("insertEmployeeName")</p>
            <p>Date Of Birth :    @Html.TextBox("insertDateOfBirth")</p>
            <p>Date Of Joining :  @Html.TextBox("insertDateOfJoining")</p>
            <p>Supervisor :       @Html.TextBox("insertSupervisor")</p>
            @*<input type="submit" id="insertOK" value="Ok" style="margin-left:20%; float:left" />
            <input type="submit" id="insertCancel" value="Cancel" style="margin-right:40%; float:right" />*@
        </div> 

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to Main Page", "Index")
</div>

Now when i put a break point in the home controller for calling the "Insert" view it is not going in the ajax request condition and ajax is not calling. please help?

1
Not a lot makes sense here. You have a AjaxBeginForm() then inside that you trying to insert a partial containing Html.BeginForm() (nested forms are invalid and not supported). Then the controls in the partial don't appear to relate to your model so would not post back to a model anyway. Then you loading multiple copies of the jquery scripts because they are in the partial and the main view. And your Index method does not even pass the model to the view. And what is <table ... runat="server" ..> And you don't appear to have included jquery-unobtrusive-ajax.jsuser3559349
@StephenMuecke isn't jquery-unobtrusive-ajax.js and jquery.validate.min.js same? and that html.beginform came itself when i added a partial view of create using the defined model. and what is the problem with <table runat=server>??Sarthak
Oh dear. runat=server is WebForms server controls, not MVC. isn't jquery-unobtrusive-ajax.js and jquery.validate.min.js same? Of course not! And when you include it, all that will happen is you will start throwing exceptions. For example, you pass an instance of EmployeeData to a view expecting EmployeNewDBEntities.user3559349
okay i removed that both now? @StephenMueckeSarthak
still the ajax call not working.. any more things i need to do?Sarthak

1 Answers

0
votes

Please try below code

Your View will be

@model IEnumerable<learnMVC.Models.EmployeeData>   
@{
ViewBag.Title = "Index";
}

    <script lang="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

    <script>
     function showPopView() {

      $("#ReplaceSection").dialog({          //resultView
        modal: true,
        width: "auto",
        height: "auto",
        position: "center",
        resizable: false,
        closeOnEscape: true,
        open: function (ev, ui) {
        }
      });
  }
</script>

<h2 style="margin-left:40%">Index</h2> 

  <div style="float:right;">
    @Ajax.ActionLink("Create New Record", "Insert", 
        new AjaxOptions { HttpMethod = "GET", 
             InsertionMode = InsertionMode.Replace, 
             UpdateTargetId = "ReplaceSection",
             Success:"showPopView",                
             Confirm="Want to save this new record?"})
  </div>

<div id="indexDivision" style="margin-left:25%">
        <table class="Grid" cellspacing="20">
            <tr>
                <th>Employee ID</th>
                <th>Employee Name</th>
                <th>Date Of Birth</th>
                <th>Date Of Joining</th>
                <th>Supervisor</th>
                <th  colspan="2"></th>          
           </tr>

          @foreach (var p in Model)
          {
            <tr>
                <td>@p.employeeID</td>
                <td>@p.employeeName</td>
                <td>@p.dateOfBirth</td>
                <td>@p.dateOfJoining</td>
                <td>@p.supervisor</td>
                <td>@Html.ActionLink("Edit", "Edit")</td>
                <td>@Html.ActionLink("Delete", "Delete")</td>
           </tr>
          }              
        </table>

    <div id="ReplaceSection">

    </div>  
</div>

Your Partial View will be

@model learnMVC.Models.EmployeeData
@using (Ajax.BeginForm(@using (Ajax.BeginForm("InsertForm", new AjaxOptions { HttpMethod = "POST" }))) 
{ 
   @Html.ValidationSummary(true)
   <fieldset>
    <legend>EmployeNewDBEntities</legend>

    <h1 style="margin-left:30%; width: 350px;">Insert New Record</h1>

        <div id="InsertDvivision" style="margin-left:30%; width: 350px;">
            <p>Employee ID :      @Html.TextBox("employeeID")</p>
            <p>Name :             @Html.TextBox("employeeName")</p>
            <p>Date Of Birth :    @Html.TextBox("dateOfBirth")</p>
            <p>Date Of Joining :  @Html.TextBox("dateOfJoining")</p>
            <p>Supervisor :       @Html.TextBox("supervisor")</p>           
        </div> 

        <p>
        <input type="submit" value="Create" />
        </p>
      </fieldset>
   }

And your controller actions will be

public ActionResult Index()
{
    var empList = new List<EmployeeData>();      

    EmployeeData tempvar = new EmployeeData();
    tempvar.employeeID = 40;
    tempvar.employeeName = "Amit";
    tempvar.dateOfBirth = (Convert.ToDateTime("02-02-2012")).Date;
    tempvar.dateOfJoining = (Convert.ToDateTime("02-02-2012")).Date;
    tempvar.supervisor = "Head";
    empList.Add(tempvar);
    return View("Index",empList);
}


public PartialViewResult Insert()
{
    if (Request.IsAjaxRequest())
    {
        return PartialView("Insert", new EmployeeData());
    }
    return PartialView("Insert");
}      

[HttpPost]
public ActionResult InsertForm(EmployeeData model)
{       
    //do code for save
    return Json(new {Message="Successfully saved"});
}

NB:- Never use jquery library in both view and partial view.

If you want to reload your grid,you can move grid into partial view and return partial view with new data on success event of InsertForm action.

It would be helpful.