Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Unique validation
Message
 
 
General information
Forum:
ASP.NET
Category:
MVC
Environment versions
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01560641
Message ID:
01560847
Views:
45
I didn't expect this to be this hard :( Now validations fire in Edit but don't fire at all in Add although code in them is very similar. In Edit they fire on each newly added character.

Here is what I now have in my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CardNumbers.Objects;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

using DataAnnotationsExtensions;
using System.ComponentModel.DataAnnotations.Schema;

namespace CardNumbers.Models
{
    public class ClientViewModel
    {
        public Client Client { get; set; }

        [Key]
        [Editable(false)]
        [Column("ClientId", TypeName = "int")]
        public virtual int? ClientId
        {
            get
            {
                if (Client == null)
                    return null;
                else
                    return Client.Id;
            }

            set { Client.Id = value ?? 0; }
        }
        [Required]
        [DisplayName("Client No")]
        [UIHint("Number")]
        [Column("client_no", TypeName = "smallint")]
        [Remote("doesClientNoExist", "Client", HttpMethod = "POST",
            AdditionalFields = "ClientId",
            ErrorMessage = "Client Number already exists. Please enter a different Client Number.")]
        public virtual Int16 Number
        {
            get
            {
                if (Client == null)
                    return 0;
                else
                    return Client.Number;
            }

            set { Client.Number = value; }
        }

        [Required]
        [Column("client_name", TypeName = "varchar")]
        [DisplayName("Client Name")]
        [MaxLength(30, ErrorMessage = "Client Name should not be longer than 30 characters")]
        [MinLength(3, ErrorMessage = "Client Name is too short")]
        [Remote("doesClientNameExist", "Client", HttpMethod = "POST", AdditionalFields = "ClientId",
            ErrorMessage = "Client Name already exists. Please enter a different Client Name.")]
        public virtual string Name
        {
            get
            {
                if (Client == null)
                    return "";
                else 
                    return Client.Name;            
            }

            set { Client.Name = value; }
        }

        public int id { get; set; }
    }
}
I also have troubles displaying my forms as modal dialogs. I tried displaying them as separate forms also without much of success.

Here is how I re-defined my main view:
@section scripts {
    <script src="@Url.Content("~/Scripts/Clients.js")" type="text/javascript" ></script>
}

<form id="frmClientsSearch">
    <label for="clientNo">Client No: </label>
    <input type="number" name="searchClientNo" class="numericOnly" /><br />
    <label for="clientName">Client Name: </label>
    <input type="search" size="25" value="Please enter the search value" class="SelectOnEntry"
        name="searchClientName" />

    <input type="button" id="btnClientsSearch" value="Find / Refresh" />
</form>
<div style="padding-left: 150px; padding-top: 50px; padding-bottom: 50px;" id="ClientsResults">
    <table id="flexClients" style="display: none">
    </table>
</div>

<div id="editor" style ="visibility :hidden ">
    
</div>
And this is what I have in the Clients.js
var currentId = 0;

$(document).ready(function () {
    if ($('#frmClientsSearch').length === 1) {
        
        $("input[name=searchClientName]").focus();
        $("input[name=searchClientName]").select();
    }   

    var scope = $('#sform');

    $('input[type=submit]', scope).click(function (e) {
        try {
            e.preventDefault();

            if (!scope.valid()) {
                 alert('has invalid');
                return;
            }

            save(scope);
           
        } catch (e) {
            alert("Error " + e);
        }

    });
   
    $("input[name=searchClientName]").keyup(function (event) {
        
        if (event.keyCode === 13) {
            $("#btnClientsSearch").click();
        }
    });
});

// http://www.ienablemuch.com/2011/11/flexigrid-crudinline-form-with-aspnet.html
var formHtml = "";

function canRender() {
    return _canRender;
}

$(function () {
    _canRender = false;
});

$("#flexClients").flexigrid({
    url: '/Client/Client/',
    dataType: 'json',
    colModel: [
    { display: 'Client Id', name: 'Id', width: 100, sortable: true, align: 'center', hide: true },
    { display: 'Client #', name: 'Number', width: 100, sortable: true, align: 'center' },
    { display: 'Name', name: 'Name', width: 350, sortable: true, align: 'center' },
    { display: 'Contact 1', name: 'Contact1', width: 350, sortable: true, align: 'center' },
    ],
    buttons: [
    { name: 'Add', bclass: 'add', onpress: add },
    { name: 'Edit', bclass: 'edit', onpress: edit },
    { name: 'Delete', bclass: 'delete', onpress: del },
    { separator: true }
    ],
    searchitems: [
    { display: 'Client Name', name: 'Name' }
    ],
    sortname: "Name",
    sortorder: "asc",
    usepager: true,
    title: 'Clients',
    useRp: true,
    rp: 15,
    rpOptions: [5, 10, 15, 20, 25, 40],
    showTableToggleBtn: true,
    width: 900,
    onSuccess: bindDblClick,
    onSubmit: addFormData,
    hideOnSubmit: false,
    height: 'auto',
    singleSelect: true
});

//$('.flexigrid').on('dblclick', 'tr[id*="row"]', function () {
//    // console.log('mouseenter rowId: ' + $(this).attr('id').substr(3));
//    alert($(this).attr('id').substr(3));
//    //Edit();
//});

function bindDblClick()
{
    $('#flexClients tr').dblclick(function () {          
       edit('Edit');
    });
}

//This function adds parameters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit			
function addFormData() {

    //passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
    var dt = $('#sform').serializeArray();
    dt = dt.concat($('#frmClientsSearch').serializeArray());
  
    $("#flexClients").flexOptions({ params: dt });
    return true;
}

$('#sform').submit(function () {

    $('#flexClients').flexOptions({ newp: 1 }).flexReload();
 
    return false;
});

function del(com, grid) {
    try {
        var clientName = $('.trSelected td:eq(2)').text();
        if (clientName) //Variable is defined and not empty
        {
            if (confirm("Are you sure you want to delete " + $.trim(clientName) + "?")===false)
                return false;            

            $('.trSelected', grid).each(function () {
                var id = $(this).attr('id');
                id = id.substring(id.lastIndexOf('row') + 3);

                addFormData(); $('#flexClients').flexOptions({ url: '/Client/Delete/'+ id }).flexReload();
            });
        }
    }
    catch(e) {
        alert('Error ' + e);
    }
}

var $dlg = $("#editor").dialog({
    autoOpen: false,
    show: "blind",
    closeOnEscape: true,
    resizable: true,
    width: 1200,
    height: 750,
    minHeight: 600,
    minWidth: 950
});

function RunModalDialog(title, url)
{    
    if (title)
        $dlg.dialog("option", {"title": title });

    if (url)

        $dlg.load(url, function () {
            var validator = $("#sform").validate();
            if (validator)
                 validator.resetForm();
            $dlg.dialog("option", { "title": title }).dialog("open");
        });
    else
    {
        var validator = $("#sform").validate();
        validator.resetForm();
        $dlg.dialog("open");
    }
}

function add(com, grid) {
    var url = '/Client/Add/'
    //location.replace(url);
    //RunModalDialog("Create New Client",url);

    clearForm();
    $('#fntype').val('Add');
}
 
function edit(com, grid)
{
        $('.trSelected', grid).each(function () {
          
                var id = $(this).attr('id');
                id = id.substring(id.lastIndexOf('row') + 3);
                currentId = id;
                $('#fntype').val('Edit');
                var ClientName;
                ClientName =$('.trSelected td:eq(2)').text();
               var url = '/Client/Edit/' + id;            
               //location.replace(url);
               //RunModalDialog("Edit Client: " + ClientName, url);
        });

    }

function clearForm() {

    $("#sform input").val("");
}

$(function () {
    $('#btnSave').click(function () {
        //addFormData();
        
        if ($('#fntype').val() === "Add")
            $('#flexClients').flexOptions({ url: '/Client/Add/'}).flexReload();
        else
           $('#flexClients').flexOptions({ url: '/Client/Edit/'+ currentId }).flexReload();
        
        clearForm();
        $dlg.dialog('close');
        return false;
    });
});

$(function () {
    $('#btnCancel').click(function () {

        clearForm();
        $dlg.dialog('close');
        return;
    });
});

$(function () {
    $('#btnClientsSearch').click(function () {
        addFormData();
        $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
      
    });
});
So, if I try to use RunModalDialog and use div Editor to load my view , the dialog opens but it's completely blank. The form controls do not show up.

If I move the form tag inside the editor div and remove it from the _ClientForm, then the form does show up (if I use #sform for the dialog) but again Add button doesn't fire validations and Edit does fire it.

Before I added additional fields and changed my ClientViewModel to include ClientId the Add button did work correctly.

Here is what I use for Add and Edit now
public ActionResult Add()
        {
            ClientViewModel model = new ClientViewModel();            

            return View("Edit",model);
        }
        // POST: /Client/Add

        [HttpPost]
        public ActionResult Add(ClientViewModel model, FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Db.AddClient(model.Client);
                    return this.Client(collection);
                }
                return View(model);
            }
            catch
            {
                return View(model);
            }
        }
        

        // GET: /Client/Edit/5

        public ActionResult Edit(int id)
        {
            ClientViewModel model = new ClientViewModel(); 
            var client = Db.GetClientById(id);
            model.Client = client;
            
            return View(model);
        }

        //
        // POST: /Client/Edit/5
        [HttpPost]
        public ActionResult Edit(ClientViewModel model, FormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Db.UpdateClient(model.Client);
                
                    return this.Client(collection);
                }
                return View(model);
            }
            catch
            {
                return View(model);
            }
        }
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform