Tag Archives: GridView

GridView

[RESOLVED]Bind IDictionary List to MVC WebGrid

I’m dont know how to bind an IDictionary list to a MVC WebGrid. This is what I have so far

 public List<IDictionary> GetAddress()
        {
            List<IDictionary> names = new List<IDictionary>();
        //List<string> names = new List<string>();
            using (MVCDBEntities example = new MVCDBEntities())
            {
                var Uus = from U1 in example.Users where U1.Name != null select U1;
                names = Uus.OfType<IDictionary>().ToList();
            }
            return names;
        }

I now need to some how bind  this to a webgrid, how would I achieve this ?

Hi,

taken from

http://forums.asp.net/t/1719060.aspx?Binding+MVC3+webgrid+from+DataTable+AsEnumerable+:

Model method:

public List<IDictionary> FetchEmployeeDetails()
         {
             DataSet dsEmployee = new DataSet();
             DbCommand dbCmd = m_DbAccess.SqlDb.GetStoredProcCommand("Test_FetchEmployeeDetails");
             dbCmd.CommandType = CommandType.StoredProcedure;
             dsEmployee = m_DbAccess.SqlDb.ExecuteDataSet(dbCmd);

             return ConvertToListDictionary(dsEmployee.Tables[0]);
         }

Controller Code:

public ActionResult FetchDataForGrid()
         {
             EmployeeModels modelObject = new EmployeeModels();
             var resultSet = modelObject.FetchEmployeeDetails();
             return View(resultSet);
        }

View Code:

@using System.Dynamic
 @model List<System.Collections.IDictionary>
 @{
     var result = new List<dynamic>();

     foreach (var emprow in Model)
     {
         var row = (IDictionary<string, object>)new ExpandoObject();
         Dictionary<string, object> eachEmpRow = (Dictionary<string, object>)emprow;

         foreach (KeyValuePair<string, object> keyValuePair in eachEmpRow)
         {
             row.Add(keyValuePair);
         }
         result.Add(row);
     }
     var grid = new WebGrid(result);
 }

 @if (@Model != null)
 {
     @grid.GetHtml(tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt");
 }

Grz, Kris.

Thanks for the reply, I am just getting an error with the IDictionary list anyways thanks for your time.  Is there anyway you can just use a asp.net Gridview control with something like this with the entity framework ? As binding data to a webgrid in mvc
is a joke, so much extra work, in php its easier than this

Hi,

you can’t really make use of the gridview in MVC.

What you can do, and what I did in the past, is make use of jqGrid and bind the grid client side. There are also commercial tools for this like KendoUI and others.

Grz, Kris.

[RESOLVED]get the selected rows first field id value for jqgrid using jquery

hi

i need a cell value for selected rows  first field id value for jqgrid using jquery

please someone help for me.

In JavaScript:

var rowid = $('#YourGridId').jqGrid('getGridParam', 'selrow');

// assign the value from a cell in the selected grid row to a variable of your choice:
var YourCellValue = $('#YourGridId').jqGrid('getCell', rowid, 'YourCellId')

alert(YourCellValue);

thanks for u reply

how to call on select row function for jqgrid in jquery.

Hi Ananth,

Sample for onSelectRow

 $(document).ready(function() {
        $(function() {
            $('#Listing').jqGrid({
                url: '@Url.Action("Grid", "Name")',
                datatype: "json",
                edit: false,
                add: false,
                del: false,
                height: 330,
                mtype: 'GET',
                colNames: ['ID','Name'],
                jsonReader: {
                    root: "Clients",
                    page: "CurrentPage",
                    total: "TotalPages",
                    records: "TotalRecords",
                    repeatitems: false,
                    cell: "",
                    id: "0"
                },
                colModel: [
                    { name: 'Id', index: 'Id', width: 65, align: 'center', sorttype: "int" },
                    { name: '@NameMap.STATUS_COLUMN', index: '@NameMap.STATUS_COLUMN', width: 140, align: 'left', sortable: true }],
                pager: '#pager',
                rowNum: 10,
                rowList: [10, 15, 20],
                sortname: 'Id',
                sortorder: 'asc',
                viewrecords: true,
                gridview: true,                    
                onSelectRow: function (id) {
                        $.ajax({
                                url: '@Url.Action("Details","Name")',
                                data: { 'Id': id },
                                success: function (detailsHtml) {
                                         $('#NameDetails').html(detailsHtml);
                                         },
                                dataType: 'html'
                                });
                        },
                loadComplete: function () {
                              $('#NameDetails').html("");
                             }  
            });
        });
    });

k thank you

i get back to you soon……

[RESOLVED]how to add,edit,delete records using gridview in mvc .I want to use dropdown list ,radio button inside grid

Hi

i want to  add,edit,delete records using gridview in mvc .I want to use dropdown list ,radio button inside grid.

Also I want to use dropdownlist  to fetch data from database in cshtml page.

Please help me.

Thanks and Regards

chandran

You can’t use gridview in asp.net MVC, which is a server control avail in ASP.Net WebForm applications.

In MVC, you can go with the "webgrid" as the previous poster said.

Hi rchandran.nr,

Thanks for your post.

According to your description,

rchandran.nr

how to add,edit,delete records using gridview in mvc .I want to use dropdown list ,radio button i

As community member mentioned,there’s no server control(Gridview) in mvc,you can use webgrid,please refer to this:

Inline Editing With the WebGrid in ASP.NET MVC 4

And you can check this:http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/

Hope this can be helpful.

Best Regards,

Eileen

[RESOLVED]Create a gridview like structure in MVC 5 Razor.

Hello All,

I am new to MVC Concept , so the question may be a dumb one , but i wanted to know , my requirement goes like this:

I have a table with come columns and according to the column values i need to show textbox or dropdownlist (like we used to do in gridivew template field with some conditions.) , since this is mvc and i suppose there is nothing called as gridview as all
the controls are html so m blind at this point , where shall i start ? Morover i need to edit and delete rows also. 

Any tutorials on how to handle these kind of situations ?

A few suggestions are here

http://stackoverflow.com/questions/177275/grid-controls-for-asp-net-mvc

A quick glance show that most are javascript based, if you want something that works without js then you’ll probably need to do your own.  Rather than using an off-the-shelf component you could use this as an opportunity to learn http and mvc and how they
work, as it will see you in good stead for the future.  You don’t want to be one of those developers that has to constantly come here to ask people to do their work for them.

[RESOLVED]what is equivalent of RowDataBound event of Web Form gridviews in MVC grids ?

Hello,

I am new-by on MVC. I have developed a web application on Web Forms which is heavily data driven from a database.  So that i had to use Gridview control in many pages. The beauty of gridview control for me is that i am able to access any controls on RowDatabound,
then i can change them in different ways (colors, visibility, formatting etc) depending on the business logic.

As far as I know, MVC has totally different life cycle where I cannot find any "rowDataBound" event. How would I change controls (colors, visibility etc) in grids depending on the business logic. Say that I have very small grid and I need to change TextBox
color into "RED" if gridview Rownumber is greater then 10? Where should we consider all these logics in MVC?

Thanks

If you are using the WebGrid class, you can apply simply logic in the format parameter. For example, if you wanted to return red if the Amount property/column is greater than 10, yu can do it like this:

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("Amount", "Amount", format: @<span style="color:@(item.Amount > 10 ? "red;" : "black;)">@item.Amount</span>)
    )
)

[RESOLVED]how can I upload an image and save the url in the database

I want to be able to upload an image to the server but instead of saving the image as byte in the database I want to save the path so that in the view page I call the image by it’s path.also the image when uploaded it should be uploaded in a certain
folder if folder not found create one.all this should be using MVC5 any help is really appreciated

lolo512

I want to be able to upload an image to the server but instead of saving the image as byte in the database I want to save the path so that in the view page

And the problem is …? To save use File.WriteAllBytes. 

I want a full code I don’t know how to do so im a new learner of MVC I appreciate your help

Hi,

For your references:

  1. https://www.youtube.com/watch?v=9LPIu_BvatE
  2. https://www.youtube.com/watch?v=rpmtFvduwyI

Here I do for both save to database or (not and) to a folder, depend on it’s size:

A helper class, is used when save to database:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;

namespace PersonEntity.Model
{
    public static class ConvertFile
    {
        public static byte[] ImageToByte(HttpPostedFileBase imageFile)
        {
            if (imageFile == null) { return null; }
            return (imageFile.ContentType == "image/jpeg" || imageFile.ContentType == "image/gif" || imageFile.ContentType == "image/png") ? FileToByte(imageFile) : null;
        }

        public static byte[] FileToByte(HttpPostedFileBase file)
        {
            byte[] data = new byte[file.ContentLength];
            file.InputStream.Read(data, 0, file.ContentLength);
            return data;
        }
    }
}

Need a partial class to the class where image class is defined, for "File":

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PersonEntity.Model
{
    [MetadataType(typeof(ProductPhotoMetadata))]
    public partial class ProductPhoto
    {
        [DisplayFormat(NullDisplayText = "n/a")]
        //[Required(ErrorMessage = "Please select image file")]
        public HttpPostedFileBase File { get; set; }
    }
}

Controller, add ",File" almost at the end of the "public Action Result:…….,File")] ProductPhoto…….. It si boleded and underlined

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

        // GET: ProductPhotoes/Create
        public ActionResult Create()
        {
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria");
            return View();
        }

        // POST: ProductPhotoes/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 = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
        {
            productPhoto.ModifiedDate = DateTime.Now;
            if (productPhoto.File != null)
            {
                if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
                {
                    ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                    return View(productPhoto);
                }
                productPhoto.ImageSize = productPhoto.File.ContentLength;

                /** Photo dibawh 61KB disimpan di database, sisanya disimpan di folder, dengan nama NewGuid() **/
                if (productPhoto.File.ContentLength < 61676)
                {
                    productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
                }
                else
                {
                    productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
                    productPhoto.Photo = null;
                    var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
                    productPhoto.File.SaveAs(path);
                }
            }

            if (ModelState.IsValid)
            {
                db.ProductPhotoes.Add(productPhoto);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

        // GET: ProductPhotoes/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
            if (productPhoto == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

        // POST: ProductPhotoes/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,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
        {
            productPhoto.ModifiedDate = DateTime.Now;

            if (productPhoto.File != null)
            {
                if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
                {
                    ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
                    return View(productPhoto);
                }
                productPhoto.ImageSize = productPhoto.File.ContentLength;
                if (productPhoto.File.ContentLength < 61676)
                {
                    productPhoto.PhotoFileName = null;
                    productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
                }
                else
                {
                    productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
                    productPhoto.Photo = null;
                    var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
                    productPhoto.File.SaveAs(path);
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(productPhoto).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
            return View(productPhoto);
        }

Create.cshtml, attention on "@using (Html.BeginForm(…………………..))"

@model PersonEntity.Model.ProductPhoto

@{
    ViewBag.Title = "Create: " + @EstateAgency.Admin.Resource.Product + " Photo";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("Create", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ProductPhoto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.File, new { type = "file" })
                @Html.ValidationMessage("CustomError")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
            </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>
}

<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Edit.cshtml, attention on @using same with Create.cshtml:

@model PersonEntity.Model.ProductPhoto

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm("Edit", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ProductPhoto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.File, new { type = "file" })
                @Html.ValidationMessage("CustomError")
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PhotoFileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargePhoto, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargePhoto, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargePhoto, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargePhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargePhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargePhotoFileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ImageSize, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ImageSize, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", 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>
}

<div>
    <br />
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

You may need to modify Web.config for larger file, add "maxRequestLength="2097152":

  <system.web>
    <globalization culture="auto" uiCulture="auto" />
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" maxRequestLength="2097152" />
  </system.web>

Have fun

Hi lolo512,

Thanks for your post.

According to your description,

lolo512

how can I upload an image and save the url in the database

Here is a sample,you can refer to the following code snippet:

table:

CREATE TABLE [dbo].[tblA]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [fname] NVARCHAR(50) NULL, 
    [lname] NVARCHAR(50) NULL, 
    [imageUrl] NVARCHAR(50) NULL
)
  • Creat an "Images" folder in Solution explorer.
  • Create an ADO.NET Entity Data Model (in this example is "Database1Entities") 
  • Home Controller: 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace test2.Controllers
    {
    public class HomeController : Controller
    {
    public ActionResult Index()
    {
        return View();
    }
    
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
    
        if (file != null)
        {
            Database1Entities db = new Database1Entities();
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath =Server.MapPath("~/images/"+ ImageName);
    
            // save image in folder
            file.SaveAs(physicalPath);
    
            //save new record in database
            tblA newRecord = new tblA();
            newRecord.fname = Request.Form["fname"];
            newRecord.lname = Request.Form["lname"];
            newRecord.imageUrl = ImageName;
            db.tblAs.Add(newRecord);
            db.SaveChanges();
    
        }
        //Display records
        return RedirectToAction("../home/Display/");
    }
    
    public ActionResult Display()
    {
        return View();
    }
    }
    }
  • Index View 

    @{
       ViewBag.Title = "Index";
    }
    
    @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
                        new { enctype = "multipart/form-data" }))
    {
    <div>
    First name<br />
    @Html.TextBox("fname") <br />
    Last name<br />
    @Html.TextBox("lname") <br />
    Image<br />
    <input type="file" name="file" id="file" style="width: 100%;" /> <br />
    <input type="submit" value="Upload" class="submit" />
    </div>    
    }
  • Display View 

    @{
        ViewBag.Title = "Display";
    }
    
    @{
       test2.Database1Entities db = new test2.Database1Entities();
    }
    @using (Html.BeginForm())
    {
    <table border="1">
    <thead>
        <tr>
            <th>Image</th>
            <th>First name</th>
            <th>Last name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in db.tblAs)
        {
            <tr>
                <td><img src="~/images/@item.imageUrl" width="100" height="100" /></td>
                <td>@item.fname</td>
                <td>@item.lname</td>
            </tr>
        }
    </tbody>
    </table>
    }

Output:

/Home/ 

/home/Display/ 

More information:

http://forums.asp.net/t/1981336.aspx?Storing+Image+Url+in+Database

http://stackoverflow.com/questions/17499259/upload-a-picture-to-a-database-in-asp-mvc-4

Hope this can be helpful.

Best Regards,

Eileen

thank you for the reply it was very helpful. I need help in one more thing, instead of first and last name I have category which I am supposed to read from a database table category (ID-categoryName) and depending on the selected value the images is saved
in a folder of that selected value.

for example selected value :basketball.

the image path is: ~/basketball/fileName

can you help me with that??

[RESOLVED]bind data to a view in aspx page in asp.net mvc using C# and sql server stored prodcedure

Hi Experts,

I am totally new to ASP.NET MVC.

So Please try to help me out here?

I Created a ASP.NET MVC 4 Application with ASPX view.

I have a database and have a stored procedure in it named usp_getstudents which retrieve all the student information like Studentid, studentname , studentage and studentemail.

I want to display these details in  a view.

So how to do achieve this using Model, control and View.

How the design should be?

Can any one help me here with sample code snippets.

I am using ASP.NET MVC,C# and ASPX views and SQL Server Stored Procedure

Thanks a lot in advance.

 

 

Hi,

As you are using ASPX view, you can probably use GridView kind of controls as explained in this article:

http://www.binaryintellect.net/articles/59b91531-3fb2-4504-84a4-9f52e2d65c20.aspx

Note: Source code can also be downloaded at the end of the page.

Thanks for your valuable reply. But Sorry as this was not the concern i asked. It was just to display some text from database in html in MVC.

Hi,

In fact the example has asp:GridView control which is a bit advanced control.

You can even place asp:Label controls in the page and you can fill in Page_Load event (If you see in the example, gridView is being populated with it’s DataSource in Page_Load event).

In your case, you would want to just set the Text properties to the appropriate values from DB.

With in page_load you can invoke your DB layer to get the required objects and fill in the UI controls (setting Text properties for example) with the returned object from Data access layer.

The close sample I could find is of MVC2 (as most of the samples are on razor) but this article is a good starter to understand how MVC works (especially for aspx engine) across layers in single article:
http://weblogs.asp.net/scottgu/asp-net-mvc-framework-part-1

There are quite a few things changed though later, for example, ControllerAction attribute is not required now, RenderView method is replaced with View() method etc.

If you would like to see the current syntax for aspx engine, you can try Scaffolding feature and generate the code and look at the generated code for View and you can get an idea of the syntax and samples more.

Also note, in the example, Entity Framework is used, but you can write ADO.NET code or use any other convenient data access frameworks to accomplish the task according to your requirement.

Hi vickeynet,

For this requirement, you could use WebGird.

# WebGrid with custom paging and sorting in MVC4

http://www.dotnet-tricks.com/Tutorial/mvc/GK2W110113-WebGrid-with-custom-paging-and-sorting-in-MVC4.html

Best Regards

Starain

Hello Vickey,

There are plenty of ways to achieve this requirement , a common implementation is shown below:try to understand:

1) Create a model that will help communicate values between view and the controller.

public class Student
{
    public string StudentID {get;set;}
    public string StudentName {get;set;}    
    ....
}

2) Get the values from database in a specific controller:

public ActionResult Students()
{
    String connectionString = "<THE CONNECTION STRING HERE>";
    String sql = "SELECT * FROM students";
    SqlCommand cmd = new SqlCommand(sql, conn);

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        var model = new List<Student>();
        while(rdr.Read())
        {
            var student = new Student();
            student.StudentID= rdr["StudentID"];
            student.StudentName= rdr["StudentName"];           
            ....
            model.Add(student);
        }
    }
    return View(model);
}

3) Lastly take the records and display it in respective view:

@model List<Student>

<h1>Student</h1>

<table>
    <tr>
        <th>StudentID</th>
        <th>StudentName</th>
        ...
    </tr>
    @foreach(var student in Model)
    {
    <tr>
        <td>@student.StudentID</td>  
        <td>@student.StudentName</td>  
        ...
    </tr>
    }
</table>

Hope This Helps.

Feel free to ask any question regarding the same.

Have a great day. :)

[RESOLVED]How to bind dynamically the Columnnames,Column values,and Data in jqgrid?

public JsonResult GridRecords1()
{ 
//var records = objInstituteRegistrationBusiness.GridRecords();
////return Json(records, JsonRequestBehavior.AllowGet); 
//dynamic obj;
//obj = objInstituteRegistrationBusiness.GridRecords();
//DataTable dt = GetDataTableFromObjects(obj);

//var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//string jsonString = javaScriptSerializer.Serialize(records);
//return Json(jsonString, JsonRequestBehavior.AllowGet);
var result = new
{
Json = new
{
colNames = new[]
{
"institutionid","institutionname", "displayname", "shortname","supportedfield","schemename","subscriptionto"
},

colModels = new[]
{ 
new { name= "institutionid", hidden= false, sortable= true, sorttype= "int", formatter= string.Empty, formatoptions = string.Empty },
new { name= "institutionname", hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "displayname", hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "shortname" ,hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "supportedfield",hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "schemename", hidden= false, sortable= true, sorttype= "string", formatter= string.Empty, formatoptions = string.Empty },
new { name= "subscriptionto", hidden= false, sortable= true, sorttype= "string", formatter= "date", formatoptions = "dd/mm/YYYY" }

},
data = new
{
options = new
{
page = "1",
total = "1",
records = "1",
rows = new[] {
new{institutionid=1,institutionname="test",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="20/11/2014" },
new{institutionid=12,institutionname="test2",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/03/2014" },
new{institutionid=11,institutionname="test3",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/11/2014" },
new{institutionid=10,institutionname="test4",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/11/2014" },
new{institutionid=9,institutionname="test5",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/11/2014" },
new{institutionid=5,institutionname="test6",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/12/2014" },
new{institutionid=3,institutionname="test7",displayname="test",shortname="test",supportedfield="test",schemename="test",subscriptionto="15/01/2014" }, 
}
}
}
}
};
//return Json(result);
return Json(result, JsonRequestBehavior.AllowGet);
}



[Authorize]
public ActionResult GridViewInstituteDynamicBinding()
{
return View();
}



View:

<script src="../Scripts/jqGrid/i18n/grid.locale-en.js"></script>


<table id="list2">

</table>

<div id="pager2"></div>

<table id="grid-table"></table>

<div id="grid-pager"></div>


<script type="text/javascript">
$.extend(
$.jgrid.search,
{
closeOnEscape: true,
closeAfterSearch: true,
//closeAfterReset:true,
overlay: 0,
Reset: "Reset",
Find: "Find"
}
);

var recordids = new Array();

jQuery(function ($) {
var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";

//resize to fit page size
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
})
//resize on sidebar collapse/expand
var parent_column = $(grid_selector).closest('[class*="col-"]');
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 0);
}
})


var selaArrr = [];

jQuery(grid_selector).jqGrid({
//direction: "rtl",

//subgrid options
subGrid: false,
//subGridModel: [{ name : ['No','Item Name','Qty'], width : [55,200,80] }],
//datatype: "xml",
subGridOptions: {
plusicon: "ace-icon fa fa-plus center bigger-110 blue",
minusicon: "ace-icon fa fa-minus center bigger-110 blue",
openicon: "ace-icon fa fa-chevron-right center orange"
},
///veera

multiselect: true, 
onSelectRow: function (id, status, e)
{

},
onSelectAll: function (aRowids, status,id,e)
{
recordids = [];

if (status)
{
//$('#add_grid-table').hide();
//$('#edit_grid-table').hide();
}
else {
//$('#add_grid-table').show();
//$('#edit_grid-table').show();
}
for (var i = 0; i < aRowids.length; i++)
{
var myGrid = $('#grid-table'),
// selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'),
cellValue = myGrid.jqGrid('getCell', aRowids[i], 'institutionid');
recordids.push(cellValue);
}


},
ondblClickRow: function (rowid, iRow, iCol, e)
{
var myGrid = $('#grid-table'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'),
cellValue = myGrid.jqGrid('getCell', rowid, 'institutionid');
window.location = "../Ace/EditRecord?rowid=" + cellValue + "&operation=ViewRecord";
},

//for this example we are using local data
subGridRowExpanded: function (subgridDivId, rowId) {
var subgridTableId = subgridDivId + "_t";
$("#" + subgridDivId).html("<table id='" + subgridTableId + "'></table>");
$("#" + subgridTableId).jqGrid({
datatype: 'json',
data: subgrid_data,
colNames: ['ID', 'Institution Name', 'Short Name', 'Board of Education', 'Website Address'],
colModel: [
{ name: 'id', width: 50 },
{ name: 'name', width: 150 },
{ name: 'qty', width: 50 }
]
});
},



url: "../Ace/GridRecords1",
datatype: "json",
height: 250, 

//Here i need to bind the Controller Data,Column model,Column names dynamically But now i have to give colNames: ['ID', 'Institution Name', 'Display Name', 'Short Name', 'Board of Education', 'Scheme Name','Subscription Date'], colModel: [ { name: 'institutionid', hidden: true, sortable: true, sorttype: "int" }, { name: 'institutionname', sortable: true }, { name: 'displayname', sortable: true }, { name: 'shortname' ,sortable: true}, { name: 'supportedfield', sortable: true }, { name: 'schemename', sortable: true }, { name: 'subscriptionto', hidden: true, sortable: true, formatter: "date", formatoptions: { newformat: "d/m/Y" } } ], viewrecords: true, rowNum: 10, height: '350px', loadtext: "Processing pending request data please wait...", rowList: [10, 20, 30], idsOfSelectedRows: [], pager: pager_selector, reloadAfterSubmit:true, altRows: true, sortorder: "ASC", loadonce: true, //toppager: true, multiselect: true, scrollerbar:true, //multikey: "ctrlKey", multiboxonly: true, afterSubmit: function () { $(grid_selector).jqGrid().setGridParam( { datatype: "json", page: 1, url: "GridRecords", } ).trigger("reloadGrid"); }, onSelectRow: function (id, isSelected,status) { var p = this.p, idsOfSelectedRows = p.idsOfSelectedRows, item = p.data[p._index[id]], i = $.inArray(id, idsOfSelectedRows); item.cb = isSelected; if (!isSelected && i >= 0) { idsOfSelectedRows.splice(i, 1); // remove id from the list recordids.splice(i, 1); // remove id from the list if (recordids.length == 1 || recordids.length == 0) { //$('#edit_grid-table').show(); } else { //$('#edit_grid-table').hide(); } if (recordids.length == 0) { //$('#add_grid-table').show(); } else { //$('#add_grid-table').hide(); } } else if (i < 0) { idsOfSelectedRows.push(id); var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', id, 'institutionid'); recordids.push(cellValue); if (recordids.length == 1 || recordids.length == 0) { //$('#edit_grid-table').show(); } else { //$('#edit_grid-table').hide(); } if (recordids.length == 0) { //$('#add_grid-table').show(); } else { //$('#add_grid-table').hide(); } } }, loadComplete: function () { var table = this; setTimeout(function () { styleCheckbox(table); updateActionIcons(table); updatePagerIcons(table); enableTooltips(table); }, 0); }, //editurl: "DeleteRecord",//nothing is saved caption: "Registered Institutes" }); $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size function aceSwitch(cellvalue, options, cell) { setTimeout(function () { $(cell).find('input[type=checkbox]') .addClass('ace ace-switch ace-switch-5') .after('<span class="lbl"></span>'); }, 0); } //enable datepicker function pickDate(cellvalue, options, cell) { setTimeout(function () { $(cell).find('input[type=text]') .datepicker({ format: 'dd/MM/yyyy', autoclose: true }); }, 0); } //navButtons jQuery(grid_selector).jqGrid('navGrid', pager_selector, { //navbar options edit: true, editicon: 'ace-icon fa fa-pencil blue', add: true, addicon: 'ace-icon fa fa-plus-circle purple', del: true, delicon: 'ace-icon fa fa-trash-o red', search: true, searchicon: 'ace-icon fa fa-search orange', refresh: true, refreshicon: 'ace-icon fa fa-refresh green', view: true, viewicon: 'ace-icon fa fa-search-plus grey', view: true, edit: true, add: true, del: true, view: true, editfunc: function () { var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', selectedRowId, 'institutionid'); window.location = "../Ace/EditRecord?rowid=" + cellValue + "&operation=EditRecord"; }, addfunc: function () { var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', selectedRowId, 'institutionid'); // Add(); window.location = "../Ace/Aceadmin?operation=Addrecord"; }, delfunc: function (id, status, e) { $.alert.open({ type: 'confirm', content: 'Do you want to delete the selected Institute?', callback: function (button) { if (button == 'yes') { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: "{'recordid':'" + recordids + "'}", url: "../Ace/DeleteRecord", dataType: "html", success: function (data) { var msg = jQuery.parseJSON(data); $('.deletealert').html('<button type="button" class="close" data-dismiss="alert">'+'<i class="ace-icon fa fa-times"></i>'+ '</button>'+'<b>Success!</b>' + " " + msg.Message); $('.deletealert').css("display", "block"); window.setTimeout(function () { $('.deletealert').css("display", "none"); }, 5000); $('#edit_grid-table').show(); $('#add_grid-table').show(); $(grid_selector).jqGrid().setGridParam( { datatype: "json", page: 1, url: "GridRecords", } ).trigger("reloadGrid"); recordids.splice(0, recordids.length); }, error: function (xhr, ajaxOptions, thrownError) { //alert(thrownError); $.alert.open({ title: 'Warning', type: 'warning', content: thrownError }); } }); } } }); }, viewfunc: function () { var myGrid = $('#grid-table'), selectedRowId = myGrid.jqGrid('getGridParam', 'selrow'), cellValue = myGrid.jqGrid('getCell', selectedRowId, 'institutionid'); window.location = "../Ace/EditRecord?rowid=" + cellValue + "&operation=ViewRecord"; } }, { recreateForm: false, }, { closeAfterAdd: true, recreateForm: true, viewPagerButtons: false, beforeShowForm: function (e) { var form = $(e[0]); form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar') .wrapInner('<div class="widget-header" />') style_edit_form(form); } }, { //delete record form recreateForm: true, beforeShowForm: function (e) { var form = $(e[0]); if (form.data('styled')) return false; form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />') style_delete_form(form); form.data('styled', true); }, onClick: function (e) { alert(1); } }, { //search form recreateForm: true, afterShowSearch: function (e) { var form = $(e[0]); form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />') style_search_form(form); </script>

Instead of posting the entire code, please point out the code you are having problem.

Hi,

For this requirement, please refer to this links below:

# Jqgrid with dynamic colNames?

http://stackoverflow.com/questions/13452132/jqgrid-with-dynamic-colnames

# Dynamic column genrate jqgrid in asp.net mvc razor

http://feel-tech-evolution.blogspot.jp/2013/07/dynamic-column-genrate-jqgrid-in-aspnet.html

Best Regards

Starain

[RESOLVED]Table inside Table

Hi,

 I want to design a concept similar like nested gridview.But i dont want table inside a table. Is there any way to do it.pls help.

You can use a listview which allow you to control the rendered html. You might use divs instead. 

You can show/hide div also insted of table.

dear komaldparekh,

                                can you give me a example for this.

Hi vignesh,

Thanks for your post.

komaldparekh

You can show/hide div also insted of table.

The <div> element and <table> element are often used as a layout tool, If I don’t misunderstand, komaldparekh recommend to use <div> element instead of <table> element. Besides, here is a good article which describes why do developers move form table-based
website structures to div-based structures, you could refer to it.

If you have any question about this issue, please post back freely.

Best Regards,

Fei Han

What sort of data are you displaying in your grid/nested data?

If it’s tabular data, use a table – that’s what tables are for. A gridview is typically used for displaying tabular data so it makes sense to render it as a table. If you have nested data that is also tabular, that should also be rendered as a table. 

How to open a pop up window when pressing F1 from a particular textbox?

Hi Fiends,

I have a textbox txtEmpID to enter the Employee ID. If the person has a doubt, then he needs to press F1 to open a pop up window which contains the list of all employee ID’s and names. How can i do this. is there any event like keypress? Some one please
help me.

This is my textbox.

<asp:TextBox ID="txtEmpID" runat="server" AutoPostBack="True"></asp:TextBox>

Thanks in advance.

Capturing function key (F1-F12) keypress events can be tricky as most of them are already mapped to existing functions within their respective browsers (I believe that F1 is traditonally a "help" key).

Generally, you would be able to capture the event much like you would within a standard element by using the onkeyup (or onkeydown) event as seen below :

<!-- When the onkeyup event is triggered, check for a new window -->
<asp:TextBox ID="txtEmpID" runat="server" AutoPostBack="True" onkeyup='CheckForNewWindow();'></asp:TextBox>

<!-- Script to check for keypress -->
<script type='text/javascript'>
   function CheckForNewWindow(){
       // Grab the key that was pressed and if it was 112 (F1 key), then open a new window
       if((event.which || event.keyCode) == 112){
             // Open a new window here
             window.open('...');
       }
   }
</script>

Additionally, you might be able to
use a solution similar to the one recommended here
, which attempts to override the existing "onhelp" event for the browser and allow you to define your own event instead :

// Internet Explorer
if ("onhelp" in window)
    window.onhelp = function () { 
        showMyHelpInsteadOfTheUsualDefaultHelpWindow(true); 
        return false;
    }
// Others
else {
    document.onkeydown = function(evt) {
        cancelKeypress = (evt.keyCode == 112);
        if (cancelKeypress) {  // F1 was pressed
            showMyHelpInsteadOfTheUsualDefaultHelpWindow(true);
            return false;
        }
    }

    // Additional step required for Opera
    document.onkeypress = function(evt) {
        if (cancelKeypress) 
            return false;
    }
}

Hi Friend,

Thanks for the Reply. I tried 1st part of your code and its working fine for F2 key. I need 1 more help from you. When the pop up window opens, it has a gridview with 2 columns Emp ID and Emp Name. When i double click on Emp ID of any row, that Emp ID should
come to the textbox and the pop up window should close.Can u please tell me how should i change my below code.

Textbox from where we are pressing F2.

<asp:TextBox ID="txtEmpID" runat="server" CssClass="txtbox" Width="64px" AutoPostBack="True" style="font-size: x-small" onkeyup=’CheckForNewWindow();’></asp:TextBox>

<script type=’text/javascript’>

function CheckForNewWindow() {

if ((event.which || event.keyCode) == 113) {

window.open("EmployeeSearch.aspx", ‘Employee Search’, ‘height=500,width=380′)}

}</script>

New window opened.

Protected Sub GvEmpSearch_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvEmpSearch.RowDataBound

Dim js As String

If e.Row.RowType = DataControlRowType.DataRow Then

e.Row.Attributes("ondblclick") = "analyseRow(this)"

End If

End Sub

<script type="text/ecmascript">

function analyseRow(row) {

alert(row.cells[0].innerText);

}

</script>

The correct cell value is appearing in the alert window.How can i bring it to the above textbox? Please help.

Thanks.

Some one please help…Its really urgent for me.