ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET MVC 4 Hosting :: Partial View in ASP.NET MVC 4

clock November 22, 2013 10:10 by author Mike

Partial view is like a regular view with a file extension .cshtml. We can use partial views in a situation where we need a header, footer reused for an MVC web application. We can say that it’s like a user control concept in ASP.NET. Here I am going to explain how to create a partial view in an MVC 4 ASP.NET application.

First add a view to the shared folder with the view name _Product. The best way to create a partial view is with the name preceded by '_', because the name specifying that it is reusable.

Here in this example, I am using the partial view to display the item selected in the webgrid.

@model PartialViewSample.Models.Product

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddProduct</title>    
</head>
<body>
    <div>      
           <label>Id:</label>
            @Html.TextBox("Id", Model.Id)
             <label>Name:</label>
            @Html.TextBox("Name", Model.Id)
             <label>Description:</label>
            @Html.TextBox("Description", Model.Description)
             <label>Quantity:</label>
            @Html.TextBox("Quantity", Model.Quantity)
    </div>
</body>
</html>

We can call the partial view in a normal view like:

Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);

Or

@Html.Partial("~/Views/Shared/_Product.cshtml", product);

Html.Partial returns a string, Html.RenderPartial calls Write internally, and returns void. You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial because the result will be written to the Response stream during execution. So @html.RenderPartial() has faster execution than @html.Partial() due to RenderPartial giving quick response to the output.

We can call the partial view if the grid has a selected item. The code block is shown here:

@if (grid.HasSelection)
{
    product =(PartialViewSample.Models.Product)grid.Rows[grid.SelectedIndex].Value;        
    Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);           
}



ASP.NET MVC 4 Hosting :: How to Make a CheckBoxList in ASP.NET MVC 4

clock October 22, 2013 08:30 by author Mike


This article will show you how to create check box list in ASP.NET MVC. Consider that we have a list consist of three properly Name, ID and IsSelected and we have to show a checkboxlist using this list. First create a model with these properties, consider a category model with three properties and a static method which will return list of model as below. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace Sample.Models
{
    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsSelected{ get; set; }
 
        public static List<Category> getCategory()
        {
            List<Category> category = new List<Category>()
            {
                new Category() { ID =1, Name="Cat1",  IsSelected = true },
                new Category() { ID =2, Name="Cat2",  IsSelected = false },
                new Category() { ID =3, Name="Cat3",  IsSelected = true },
                new Category() { ID =4, Name="Cat4",  IsSelected = false },
                new Category() { ID =5, Name="Cat5",  IsSelected = true },
                new Category() { ID =6, Name="Cat6",  IsSelected = false },
                new Category() { ID =7, Name="Cat7",  IsSelected = true },
                new Category() { ID =8, Name="Cat8",  IsSelected = false },
            };
            return category;
        }
    }

 

}

Add a controller where a method will return a list of model to view. We have ProductCategoryController and index method which return list of model to view as below.

namespace Sample.Controllers
{
    public class ProductCategoryController : Controller
    {
        public ActionResult Index()
        {
            List<Category> model = new List<Category>();
            model = Category.getCategory();
            return View(model);
        }
    }

 

}

Add view to this controller method. In view we have model as list of category. Now to create check box list iterate through each item of model and create checkbox list as below.

@model List<Sample.Models.Category>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Category</h2>
@using (Html.BeginForm("Index", "ProductCategory", FormMethod.Post))
{
    for (int i = 0; i < Model.Count; i++)
    {
        @Html.CheckBoxFor(m => m[i].IsSelected)
        @Html.Label(Model[i].Name);
                                           
        @Html.HiddenFor(m => m[i].Name)
        @Html.HiddenFor(m => m[i].ID)
        <br />
    }
<div>  <input type="submit" value="Go!" /></div>

}

Now, it is very Interesting thing, when you create @Html.CheckBox it will create automatically a hiddenfield for this checkbox, which will use to maintain checkbox status checked or unchecked, when this list get post to model and to get complete list at controller in post method, you have to add two more hidden field for name and ID (two other properties of list) as above.

Here is post method:

[HttpPost]
public ActionResult Index(List<Category> model)
{
    // do operation on list   

 

    return RedirectToAction("Index");


ASP.NET MVC 4 Hosting :: ASP.NET MVC Selectlist, Selectedvalue, and Dropdownlistfor

clock July 22, 2013 07:02 by author Mike

Unintuitive framework features usually end up as highly rated questions because everyone is running into the same problem with a commonly used feature. This article will be an overview of how to use drop-down lists, setting a selected item, and issues you’ll run into on a strongly typed view. The following code have been written for MVC 4.


SAMPLE MODEL

For the sake of this article, assume we have two classes, Movie and Director. In our application we want to add new movies, and select directors from a drop-down list. The classes are structured as follows.

1
2
3
4
5
6
7
8
9
10
11
12
public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual Director Director { get; set; }
    public virtual int DirectorId { get; set; }
}
public class Director
{
    public int Id { get; set; }
    public string Name { get; set; }
}


HTML.DROPDOWNLIST Vs HTML.DROPDOWNLISTFOR
To add the drop-down markup to your .cshtml page you could of course simply write out a select element by hand, but then you lose out on validation. MVC provides HTML helpers for generating common HTML elements. For an HTML select element you have two choices: Html.DropDownList and Html.DropDownListFor. The difference is the way they reference the name attribute of the resulting HTML element. DropDownList takes as it’s first argument a string that will be turned into the form field. So the call

1
@Html.DropDownList("director", directorList) //assume directorList is an IEnumerable of SelectListItem to create options from


Will result in an html element that looks like this.

1
<select id="director" name="director">...</select>


The problem with this approach is if you change the name of the property on your model from ‘director’ to ‘auteur’ you won’t get compile time checking and your form will no longer work with model binding. Html.DropDownListFor was introduced in MVC 2 and allows binding to strongly typed views. The first argument should be a lambda function that returns the model property you want the control to bind to. So in our case if the view-model includes a property DirectorId we can create a drop-down list with the code

1
@Html.DropDownListFor(viewModel => viewModel.DirectorId, directorList)


Which generates the following html

 

1
2
3
<select id="DirectorId" name="DirectorId">
...
</select>


Now if we change the name of the Director property our build will break because the lambda expression will be invalid.Note that we’re using DirectorId instead of a Director object because we likely want to store the id in a foreign key.

POPULATING DROP-DOWN LIST OPTIONS
To populate a drop-down we need to pass the HTML helper an IEnumerable. This is easily created by making a SelectList object in your controller, and passing it in via a view-model.

1
2
3
4
5
6
7
8
9
10
11
12
public ActionResult Index()
{
    var directors = new Collection
        {
            new Director {Id = 1, Name = "David O. Russell"},
            new Director {Id = 2, Name = "Steven Spielberg"},
            new Director {Id = 3, Name = "Ben Affleck"}
        };
    var selectList = new SelectList(directors, "Id", "Name");
    var vm = new ViewModel {DirectorSelectList = selectList};
    return View(vm);
}


I’ve created a collection of directors and passed it into the SelectList constructor. This collection could have been queried from a database, this sample was simply for demonstration. I’ve also supplied which fields should be the drop-down value (Id) and display text (Name). If I omitted those additional parameters the ToString method would be called on the each object to generate the item.
My drop-down list now looks like this.

 

If you don’t like passing in a SelectList as part of your model you could pass in the IEnumerable and construct the SelectList in the view, but I prefer putting as little code in the view as possible.

SETTING A DEFAULT VALUE OF THE DROP-DOWN
And here is where things start falling apart. The aforementioned StackOverflow question highlighted how hard it is to set a default value on a drop-down. The problem stems from poor documentation for DropDownListFor. There is an overload that takes a fourth parameter called selectedValue which is an object to set the value. Theoretically I should be able to have the following the default to the option with an id of 3

1
var selectList = new SelectList(directors, "Id", "Name", new {id = 3});


However the first value, David O. Russell, is still selected in the view. And as good a job as he did in Silver Linings Playbook, I want to default to Ben Affleck. The problem is by using a strongly typed view, MVC is trying to bind my DirectorId field to the DirectorId property of my model. And because I didn’t populate the DirectorId field of my view-model, MVC is defaulting the drop-down to the first value.

My solution is to set the DirectorId property of the viewmodel to the value I want defaulted as follows.

1
var vm = new ViewModel {DirectorSelectList = selectList, DirectorId = 3};


Then when my view is templated the correct option is selected.



ASP.NET MVC 4 Hosting - Fixing ASP.NET MVC 4 Web API 404

clock January 16, 2013 08:39 by author andy_yo

For a Web Service providing some REST-style URIs to access the data, I decided to use the ASP.NET MVC 4 Web API. Once developed, tested and deployed I experienced a mysterious 404 on my production server.

The Web API started originally as WCF Web API at CodePlex and is finally fully integrated within the latest .NET framework:

“ASP.NET Web API represents the joint efforts of the WCF and ASP.NET teams to create an integrated web API framework. You can get the bits and find articles, tutorials, samples and videos on the new ASP.NET Web API home page. All you have to do is to..”

The tutorials and examples for the ASP.NET Web API are overall easy to understand and you probably get access to the technology very quickly. After I set up my first Web API, which worked absolutely perfect on Windows 8, developed using Visual Studio 2012 and tested with the IIS Express, I was not able to get the bits executed on the deployment server. It’s a Windows Server 2008 R2, IIS 7.5 and a whole bunch of stuff installed using the Web Platform Installer.

Make sure the .NET Framework is installed. Probably you missed to install the 4.5 framework on the deployment server. As IIS is set up already, once again it is necessary to register ASP.NET for the latest framework by opening your command prompt and type:

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -i

Even now, I got the 404. Eventually, I got the tip to check out how the routing of extensionless URLs work in ASP.NET. By adding

<system.webServer>

<modules runAllManagedModulesForAllRequests="true" />

...

</system.webServer>

to the web.config file of my Web API  the routing seems to work fine now.

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in