My Zend Framework 2 Application has a view whereby I display a log of events, in a simple table format. I use several basic View Helpers to manipulate the presentation of the data in the table, but on these existing View Helpers all of the logic is contained to the View Helper itself, e.g:

namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;

class GetSystemName extends AbstractHelper
{
    public function __invoke($val)
    {
        if ($val == 0){
            return 'Something';
        }
        if ($val == 1){
            return 'Something else';
       }
    }
}

My requirement is to build a function GetUserName to accept user_id and perform a check on the database to display the User's name, as the ID is of no value to the person using the system.

The way I see it I can either:

A) Start a new query from within the View Helper to return what I need or B) Use a function called getUser() from within the 'User' Module / UserTable class.

The code for B is:

namespace User\Model;

use Zend\Db\TableGateway\TableGateway;

 class UserTable
 {
 protected $tableGateway;

 public function __construct(TableGateway $tableGateway)
 {
     $this->tableGateway = $tableGateway;
 }

 //..other functions

 public function getUser($id)
 {
     $id  = (int) $id;
     $rowset = $this->tableGateway->select(array('id' => $id));
     $row = $rowset->current();
     if (!$row) {
         throw new \Exception("Could not find row $id");
     }
     return $row;
 }

What is the best option? And how would I implement it?

Apologies if this is a basic questions I am quite new to MVC and Zend.

I am developing one website in mvc4. but website take too much load to open or too much take time to open. Check it out my website.

Now what can I do to speedup my website. and also load image quickly on my website.now sujjest me any solution to open mvc website fast. also use session to get session id or user on start up or in global.aspx in session start method.

Suggest me solution to reduce load of website on start up.

gloable file 
       protected void Session_Start(Object sender, EventArgs e)
        {
             int temp = 4;
            HttpContext.Current.Session.Add("_SessionCompany", temp);


        }

I have resource file in following format:

ErrorCode | Description... for example Er_5003 | Field must not be empty

Now I would like to display whole document on web page using razor. I hoped that something like this will work, but it does not.

ResourceSet resourceSet = WebShopApi.WebApi.Resources.AppResources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
            DictionaryEntry entry1 = entry;
            Html.DisplayFor(o => entry1.Key);
            Html.DisplayFor(o => entry1.Value);
}

Could someone explain me why and what could help?

Thanks

In Razor, you can do something like:

@if (TempData["whatever"] != null)
{
   blah blah
}

I want to check, in the if condition, the value of an input, for example:

<input id="hey" type="text" value="some text here"/>
@if ((#hey).value == "test")
{
   blah blah
}

Obviously, the above doesn't work, it is just to show the intention. Is it possible?

I'm french, sorry for my bad english.

I have a slow ASP.NET method who generate a file for me :

public ActionResult Method([Bind(Prefix = "Id")] Guid id)
{
    //Long work
    return File(data, "application/pdf", doc.Name + ".pdf");
}

And in my cshtml file a button (i use Razor):

<a title="Télécharger" onclick="DownloadFile('@entity.Id')"/>

And the script method :

<script>
    function DownloadFile(id) {
        var url = '@Url.Action("Method", "TheController", new { id = "Id" })'.replace('Id', id);
        $("#divLoading").show();
        $.post(url, null,
        function (data) {
            $("#divLoading").hide();
        });
    }
</script>

The divLoading :

<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px;
    top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001;
    opacity: .8; filter: alpha(opacity=70);display:none" >
    <p style="position: absolute; top: 30%; left: 45%; color: White;">
        Génération du document...<img src="../../Content/img/ajax-loader.gif">
    </p>
</div>

The C# method is called, the divLoading appear and disappear BUT the file isn't downloaded by navigator.

If i wrote : It's work. But the loader isn't present. And i want.

My question isn't how to make a loader while donwloading file, but only show the loader before the download starting.

Thanks.

I'm really new to MVC in general and trying to understand how to do things the best way. Right now I'm stuck and need a little help.

So I have this edit form where the user can change information related to a person and list his current contacts. The contact types can be something like na email, facebook, twitter, Skype etc. The form below does what i need. Lists all contacts and allows the users to change this person information.

Now I want to allow the users to add a new contact (while the rest of the form is in edit mode). For that I want to show a popup, insert the new contact, and then update the list that already exists in the form.

How can I show the popup, insert the new contact, update the contact list while maintaining the changes the user did to the other fields?

<div id='content' class="tab-content">
<div class="tab-pane active" id="tab1">
    @using (Ajax.BeginForm("Edit", "Persons", null, new AjaxOptions() { HttpMethod = "POST" }, new { @id = "editPersonForm", enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

        @Html.HiddenFor(model => model.Persons.PersonId, new { @id = "personId" })
        @Html.HiddenFor(model => model.Persons.StateId)
        <div class="row">
            <div class="col-md-6">
                <!-- Personal Information -->
                <div class="box box-danger">
                    <div class="box-body">
                        <div class="form-group">
                            <div class="col-xs-12">
                                <label>Name:</label>
                                @Html.EditorFor(model => model.Persons.Name, new { htmlAttributes = new { @class = "form-control", @placeholder = "Introduza o nome..." } })
                                @Html.ValidationMessageFor(model => model.Persons.Name, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-xs-5">
                                <label>Birth Date:</label>
                                <div class="input-group">
                                    <div class="input-group-addon">
                                        <i class="fa fa-calendar"></i>
                                    </div>
                                    @Html.EditorFor(model => model.Persons.BirthDate, new { htmlAttributes = new { @id = "BirthDate", @class = "form-control" } })
                                    @Html.ValidationMessageFor(model => model.Persons.BirthDate, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            <div class="col-xs-5">
                                <label>Gender:</label>
                                @Html.DropDownListFor(model => model.Persons.Gender, Model.AllGenders, "Seleccione...", new { @class = "form-control" })
                                @Html.ValidationMessageFor(model => model.Persons.Gender, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-xs-12">
                                <label>Country:</label>
                                @Html.EditorFor(model => model.Persons.Nacionality, new { htmlAttributes = new { @class = "form-control", @placeholder = "Introduza a nacionalidade..." } })
                                @Html.ValidationMessageFor(model => model.Persons.Name, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-xs-4">
                                <label>Has driving licence:</label>
                                @Html.CheckBoxFor(model => model.Persons.HasDrivingLicense, new { @class = "flat-green" })
                                @Html.ValidationMessageFor(model => model.Persons.HasDrivingLicense, "", new { @class = "text-danger" })
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-xs-12">
                                @if (Model.Contacts != null && Model.Contacts.Count > 0)
                                {
                                    <table id="example2" class="table table-bordered table-hover dataTable" aria-describedby="example2_info">
                                        <thead>
                                            <tr role="row">
                                                <th class="sorting_asc" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1" aria-sort="ascending">Contact</th>
                                                <th class="sorting" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1">Contact Type</th>
                                                <th class="sorting" role="columnheader" tabindex="0" aria-controls="example2" rowspan="1" colspan="1">Active</th>
                                        </thead>
                                        <tbody role="alert" aria-live="polite" aria-relevant="all">
                                            @{
                                                string cssClass = string.Empty;
                                                string activo = string.Empty;
                                            }

                                            @for (var i = 0; i < Model.Contacts.Count; i++)
                                            {
                                                cssClass = i % 2 == 0 ? "even" : "odd";

                                                <tr class="´@cssClass">
                                                    <td class=" ">@Html.DisplayFor(model => Model.Contacts[i].Contact)</td>
                                                    <td class=" ">@Html.DisplayFor(model => Model.Contacts[i].contacttypes.Name)</td>
                                                    <td class=" ">@Html.CheckBoxFor(model => Model.Contacts[i].IsActive, new { @class = "flat-green" })</td>
                                                </tr>
                                                @Html.HiddenFor(model => Model.Contacts[i].ContactsId)
                                            }
                                        </tbody>
                                    </table>
                                }
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-xs-12">
                                <input type="button" value="Add Contact" class="buttonCreate btn btn-primary btn-sm" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }
</div>

thank you all for the help.

I have created a really simple ASP.NET MVC 5 application where i want to handle the 404 exception from my Application_Error as shown in this question and in this other answer. But when i try to reach a page who don't exist (and expect my 404 page to be displayed) the source code of my custom error page is shown.

I don't want my URL to be rewrited as in this post

My project is really simple. I just added to a basic ASP.NET WebApplication with Razor:

  • an ErrorsController.cs
  • a view Http404.cshtml
  • and edited Global.asax

as shown below:

Project organisation:

Project organisation


Global.asax:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {}

    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        HttpException httpException = exception as HttpException;

        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Errors");

        if (httpException == null)
        {
            routeData.Values.Add("action", "Index");
        }
        else
        {
            switch (httpException.GetHttpCode())
            {
                case 404:
                    routeData.Values.Add("action", "Http404");
                    break; 
            }
        }

        Response.Clear();
        Server.ClearError();
        Response.TrySkipIisCustomErrors = true;

        IController errorController = new ErrorsController();
        errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    }
}

ErrorsController.cs:

public class ErrorsController : Controller
{
    public ActionResult Http404(string url)
    {
        return View("Http404");
    }
}

Http404.cshtml

@{
    ViewBag.Title = "Page not found";
}

<h2>Page not found</h2>

But then when i try to reach a page who don't exist everything i see is the source code of my 404 page: output for a non existing page:

Output when i reach a non existing page


I searched for hours in stackoverflow and other site but found nothing to help me here.

Some people use very similar code to handle the 404 exception but don't have the same result. I'm really stuck on this, i hope someone could help me, or at least show me a better approach than this answer to handle 404 exceptions in ASP.NET MVC 5.

i need a help to bind datagird with database values, with these below condition

Example : customer is a table with fields CustNo, CustName, CustPlace, CustDesignation a) data to be displayed in grid view using connection string method. b) there should be an EDIT, DELETE, UPDATE Button. c) When i click on EDIT CustPlace, CustDesignation fields to be displayed in dropdownlist display Place and Designation under it. d) I should be able to select place and designation from the dropdownlist and option to UPDATE AND SAVE. records should save with selected values.

Thanks if u anyone can help me in this..

I have tried many samples of codeproject but nothing works out.. i am not professional in development, hope some one help me in this..

Make sure CustPlace, CustDesignation fields are displayed from other table named Place and Designation.

I have a web form when i click on search button DropDownList must select the text among the Dataitems available in dropdownlist but problem with my code is that it insert the duplicate Dataitem text instead of selecting original Dataitem. Following is my code

sqlChk = s.callingSP("SP_SearchCase", txtOfficeSerialNO.Text.Trim());
    if (sqlChk.Tables[0].Rows.Count > 0)
    {
        divEmpMast.Style.Add("display", "block");

        lblMsg.Visible = false;

        txtSNO.Text = sqlChk.Tables[0].Rows[0]["SNo"].ToString();

        txtSending.Text = sqlChk.Tables[0].Rows[0]["DateOfSending"].ToString();
        if (string.IsNullOrEmpty(sqlChk.Tables[0].Rows[0]["FrmWhere"].ToString()))
        {
            // Write your Custom Code
            sqlChk.Tables[0].Rows[0]["FrmWhere"] = "None";
        }
        else
           ddlSubdistrict.SelectedItem.Text=sqlChk.Tables[0].Rows[0]["FrmWhere"].ToString();

Please help

I am developing one website in mvc4. but website take too much load to open or too much take time to open. Check it out my website.

Now what can I do to speedup my website. and also load image quickly on my website.now sujjest me any solution to open mvc website fast. also use session to get session id or user on start up or in global.aspx in session start method.

Suggest me solution to reduce load of website on start up.

gloable file 
       protected void Session_Start(Object sender, EventArgs e)
        {
             int temp = 4;
            HttpContext.Current.Session.Add("_SessionCompany", temp);


        }

I have a tree model representing a k-ary tree (i.e. nodes have a list of children). The model implements the QAbstractItemModel and its QSize span(QModelIndex) method.

Given the following k-ary tree:

      and
      / \
     /   \
    /     \
  or      or
  /\      /\ \
 /  \    /  \ \
I1  I2  I3  I4 I5

My intention is to visualize the tree in a QTableView from left to right as follows:

 ___________
| | | Item 1
| |v|_______
| | | Item 2
| |_|_______
|^| | Item 3
| | |_______
| |v| Item 4
| | |_______
| | | Item 5
|_|_|_______

Such that each node spans over all its child nodes.

I've implemented the QAbstractItemModel::span method, but it is not taken into account by the QTableView class.

When (i.e. reacting to which signal) and how should I rebuild/redraw the QTableView?

Notes:

  • The model will be a read/write model. The user will have the option to rearrange the expression tree with drag&drop.
  • Qt Version 4.8, upgrading to 5 is not an option.

Thanks in advance.

I want to edit my kendo grid pop up. I already use editor template field to my own editor. when i used my Kendo upload control to Editor pop then I don not have any idea that how to save image in database. This is my model.

[Table("IMAGESIZE")]
    public class ImageModel
    {
        [Key]
        public int IMAGESIZE_ID { get; set; }
        public string IMAGESIZE_NAME { get; set; }
        [Required]
        public string IMAGESIZE_DESC { get; set; }
        public int created_by { get; set; }
        public DateTime created_date { get; set; }
        public int modified_by { get; set; }
        public DateTime modified_date { get; set; }
    }

That is my view

@(Html.Kendo().Grid<TelerikMvcAppCombo.Models.ImageModel>()
.Name("grdImageModel")
.DataSource(datasource => datasource
    .Ajax()
    .Model(model => model.Id(p=>p.IMAGESIZE_ID))
    .Create(create => create.Action("Create", "Imagetest"))
    .Update(update => update.Action("Editing_Update", "Imagetest"))
    .Destroy(delete => delete.Action("Delete", "Imagetest"))
    .Read(read => read.Action("GetData", "Imagetest"))
        .Model(model =>
        {
            model.Field(p => p.IMAGESIZE_ID).Editable(true);
            model.Id(p => p.IMAGESIZE_ID);
            model.Field(p => p.IMAGESIZE_ID).Editable(false);
           // model.Field(p => p.isenabled).DefaultValue(true);
        })
    )
.Columns(columns =>
{
    //columns.Bound(c => c.IMAGESIZE_ID).ClientTemplate("<input type='checkbox' value #=IMAGESIZE_ID#  />").Width(50);
    columns.Bound(c => c.IMAGESIZE_ID).ClientTemplate("<input type='checkbox' value #=IMAGESIZE_ID#  />").Title("Image No");
    columns.Bound(c => c.IMAGESIZE_NAME).Width(140).Title("Image Name");
    columns.Bound(c => c.IMAGESIZE_DESC).ClientTemplate("<img src='" + Url.Content("~/Images/") + "#=IMAGESIZE_NAME#'/>").Title("Image");
    columns.Bound(c => c.created_by).Title("Created By");
    columns.Bound(c => c.created_date).Title("Created Date");
    columns.Bound(c => c.modified_by).Title("Modified By");
    columns.Bound(c => c.modified_date).Title("Modified Date");
    columns.Command(command =>
        {
            command.Edit(); command.Destroy();
        });
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable =>editable.Mode(GridEditMode.PopUp))//TemplateName("ImageModel")
.HtmlAttributes(new { style = "height: 580px;" })
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
    .Refresh(true)
    .PageSizes(true)
    .ButtonCount(5)
))

That is my Editor template

@model TelerikMvcAppCombo.Models.ImageModel

    @Html.HiddenFor(model => model.IMAGESIZE_ID)

        <h3>Customized Edit template</h3>
        @Html.HiddenFor(model => model.IMAGESIZE_ID)

       @*<div>
           @Html.LabelFor(model=>model.IMAGESIZE_ID)
       </div>
        <div>
            @Html.EditorFor(model=>model.IMAGESIZE_ID)
        </div>

       <div>
           @Html.LabelFor(model=>model.IMAGESIZE_NAME)
       </div>
        <div>
            @Html.EditorFor(model=>model.IMAGESIZE_NAME)
        </div>
        <div>
            @Html.LabelFor(model => model.IMAGESIZE_DESC)
        </div>
       *@ 
       <div>
           @using (Ajax.BeginForm("Save", "Imagetest", new AjaxOptions
            { 
                HttpMethod = "POST",    
             } ))
             {
             @(Html.Kendo().Upload()
             .Name("files")
             .Multiple(false)
             .Messages(msg => msg.Select("Browser"))
             )
            @Html.ValidationMessageFor(model => model.IMAGESIZE_DESC)
            }
          </div>

That is my controller

public class ImagetestController : Controller
    {
        ContextClass db = new ContextClass();
        // GET: /Imagetest/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create([DataSourceRequest] DataSourceRequest request,ImageModel imagemodel)
        {
            //var req = request.
            //foreach (var image in files)
            //{
            //    var filename = Path.GetFileName(image.FileName);
            //    var path = "~/Images/" + filename;
            //    var projectpath = Path.Combine(Server.MapPath("~/Images"), filename);
            //}
            //db.imageModels.Add();
            db.SaveChanges();
            return View("");
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, ImageModel imagemodel)
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, ImageModel imagemodel)
        {
            return View();
        }
        public JsonResult GetData([DataSourceRequest] DataSourceRequest request)
        {
            var list = db.imageModels.ToList();
            return Json(list.ToDataSourceResult(request));
        }
        public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
        {
            int count=0;
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    // Some browsers send file names with full path.
                    // We are only interested in the file name.
                     string name  = Path.GetFileName(file.FileName);
                     string path = Path.Combine(Server.MapPath("~/Images"), name);
                    // The files are not actually saved in this demo
                    // file.SaveAs(physicalPath);
                     count++;
                }
            }
            // Return an empty string to signify success
            return Content("");
        }
        public ActionResult Upload(ImageModel image)
        {
            return View();
        }
    }

Now when i used kendo grid pop up then how to get image name and path in create post action. so anyone can give me any solution for it. Thanks

I have the following code in controller

[HttpPost]
public ActionResult Create(AdminDetailsViewModel viewmodel)
    {
        if (ModelState.IsValid)
       {
         viewmodel.CreatedDate = DateTime.Now;
         HttpPostedFileBase file = Request.Files["ImageData"];
         if (file.FileName=="")
         {
            // file object take image from this path ("~/images/computer.png");                                       
         }                    
         ImageRepository IR = new ImageRepository();
         int i = IR.UploadImageInDatabase(file, viewmodel);
         if (i == 1)
         {
            return RedirectToAction("Index");
         }                
       }
      return View(viewmodel);
    }

Following is the view

 <div class="form-group">
  @Html.LabelFor(model => model.AdminImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />               
        </div>
 </div>

UploadImageInDatabase() function saves the image into the database

what should I write inside the if condition of Create function so that HttpPostedFileBase file object will take the file from ("~/images/computer.png"); this path if it is null

Why we register custom filter in asp.net mvc ? I have created a custom filter and that perfectly working without register like "filters.Add(new MyAuthicationFilter());".

What is exactly mean/work of registering the filter like:

filters.Add(new MyAuthicationFilter());

I need data from database on my textbox when i choose the particular data in drop-down list. I do the following code but it give me the number instead of description.

int s1 = DropDownList3.SelectedIndex;

SqlCommand query = new SqlCommand("Select description from vul_auto where finding_id= " + s1,con);

TextBox3.Text =(query.ExecuteNonQuery()).ToString();

<asp:Repeater id="RepeaterGameCatalog" runat="server">
   <ItemTemplate>
        <div>
            <div class="col-sm-4 col-md-3">
                <div class="thumbnail feature-fix">
                    <asp:Image ImageUrl='<%# Eval("GameLogo") %>' AlternateText="Game  Name"  onerror="GameImgError(this)" runat="server"/>
                    <h3 class="text-warning"><%# Eval("Name") %></h3>
                    <p><%# Eval("Comments") %></p>
                    <p class="store-links">
                        <a href="#" class="store-cont play-store"></a><a href="#" class="store-cont apple-store"></a>
                    </p>
                </div>
            </div>                            
        </div>
    </ItemTemplate>
</asp:Repeater>

I need the "Name" in the "h3" tag to adjust itself with the width of the repeater control. Or to put it simple...i would need some kind of a word wrap functionality for the "Name" in "h3"

In my app I am trying to upload an image. Image is showing in an asp image control. It works fine but when client changes the image and decides not to use the new image and wants the old image that image does not upload. I searched the net and found that the upload control saves the file name in session variable and found the following code to clear the session.

private void ClearContents(Control control)
    {
        for (var i = 0; i < Session.Keys.Count; i++)
        {
            if (Session.Keys[i].Contains(control.ClientID))
            {
                Session.Remove(Session.Keys[i]);
                break;
            }
        }
    }

The problem is that this code works fine on my local but not working on the server.

Does anyone know what I am doing wrong?

I have an ASP.NET website running with Active Directory authentication using an AD connection string. It's deployed and was working fine on a Windows Server 2012 R2 machine.

I configured the local machine's Active Directory domain for other purposes. After that, AD connection string started to produce an error in the web.config file. This does not let the site load.

Any idea why this is happening? Is there another way to access AD other than AD connection string?

How can I create dynamic database on cloud in asp.net M.V.C. ? its urgent please find me the way by which I can make dynamic database on cloud . I have my own cloud database.

I used ModalPopupExtender to popup a panel. In the panel I have a textbox. For that textbox's textchanged event i'm wrote some codes. But whenever focus come out of that textbox. The popup is closing itself immediately. Can anyone say how to resolve this issue.

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Panel ID="pnlEdit" runat="server" Width="100%"
DefaultButton="lnkbtnCancel">

<table id="tblEditUser">
                                          <tr>
                                        <td><asp:Label ID="Label1" runat="server" Text="E-mail:" CssClass="lblGray"></asp:Label></td>
                                        <td colspan="2"><asp:TextBox ID="txtEmail" runat="server" AutoPostBack="true"   ontextchanged="txtEmail_TextChanged" CssClass="txtDarkgray" Width="300px"></asp:TextBox></td>
                                    </tr>
                                    <tr>
                                        <td><asp:Label ID="Label2" runat="server" Text="Name:" CssClass="lblGray"></asp:Label></td>
                                        <td><asp:Label ID="lblName" runat="server" CssClass="lblGray"></asp:Label></td>
                                   </tr>

This might be an outdated tool, but I am trying (and have mostly succeeded) to use the scriptmanager methodology to disable my controls while my website's user is redirected. However, adding in the redirect at the end causes all the scriptmanager stuff that had been working to fail. Is what I'm trying to do not possible?