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 4.5 Hosting - How to Leverage the .NET 4.5 Model Binding and Strongly Typed Data Controls with Telerik’s ASP.NET AJAX Controls

clock May 15, 2013 10:58 by author Ben

The new release of RadControls for ASP.NET AJAX includes a ton of great new features and capabilities. This post is the second of two posts I will do over the week that elaborates on the new ModelBinding support and Strongly Typed Data Controls into the Telerik’s Ajax suite. In the previous part you learned how the Strongly Typed Data Controls work and how to select data and bind the controls via the ModelBinding capabilities available in .NET 4.5. Now you will learn how to do filtering, perform CRUD operations and validate user input when you use ModelBinding.

 

Model Binding Filtering
In order to filter the data source of the data bound control and pass the filtered data to the control you could pass filter parameters to use the SelectMethod. You could get these parameters from query string, cookies, form values, controls, viewstate, session and profile. For example:

public IQueryable<Product> GetProducts([Control("RadComboBoxCategories")] int? categoryID, [QueryString]string name)
{
    // Filter the data source based on categoryID and ProductName
}

The code snippet above will get the name parameter from the QueryString and integer value of the selected item of the Telerik’s ASP.NET ComboBox with ID equlas to “RadComboBoxCategories”.

Model Binding CRUD operations
Editing
In order to have editing enabled into the data bound controls, you need to set the UpdateMethod of the corresponding control to the web form page’s method. The UpdateMethod can have following signature:

public void UpdateProduct(int ProductID)
{
    Product updatedProduct = context.Products.Where(p => p.ProductID == ProductID).First();
   TryUpdateModel(updatedProduct);
   if (ModelState.IsValid)
   {
       context.SubmitChanges();
   }
}

Where the “ProductID” is one of the fields set as DataKeyNames of the corresponding bound control. 
Or you could use following signature:

public void UpdateProduct(Product product)
{
    Product updatedProduct = context.Products.Where(p => p.ProductID == product.ProductID).First();
    TryUpdateModel(updatedProduct);
    if (ModelState.IsValid)
    {
         context.SubmitChanges();
    }
}

Inserting
In order to have inserting enabled into the data bound controls you need to set the InsertMethod property of the corresponding control to the name of the web form page’s insert method. The InsertMethod can have following signatures:

public void InsertProduct(Product p)
{
     if (ModelState.IsValid)
     {
      context.Products.InsertOnSubmit(p);
      context.SubmitChanges();
     }
}

//OR

public void InsertProduct()
{
   Product pr = new Product();
   TryUpdateModel(pr);

    if (ModelState.IsValid)
    {
                context.Products.InsertOnSubmit(pr);
               context.SubmitChanges();
    }
}

Deleting
In order to have deleting enabled into the data bound controls you need to set the DeleteMethod property of the corresponding control to the name of the web form page’s delete method. The DeleteMethod can have following signature:

public void DeleteProduct(int ProductID)
{
   Product deletedProduct = context.Products.Where(p => p.ProductID ==
ProductID).First();
    context.Products.DeleteOnSubmit(deletedProduct);
    context.SubmitChanges();
}

ModelBinding Validation
Due to the fact that Model Binding system in Web Forms supports model validation using the same validation attributes from the System.ComponentModel.DataAnnotations you could use validation into our databound controls. You could decorate properties from your model classes with the attributes provided in System.ComponentModel.DataAnnotations namespace. For example if you have DataContext mapped to a Northwind database “Product” table and you want to ensure that when inserting new product or update existing one the ProductName field is populated, you could set [Required] attribute to it into the DataClasses.designer.cs file:

[Required]
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ProductName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string ProductName
{
     get
     {
           return this._ProductName;
     }
     set
     {
           if ((this._ProductName != value))
           {
           this.OnProductNameChanging(value);
           this.SendPropertyChanging();
           this._ProductName = value;
           this.SendPropertyChanged("ProductName");
           this.OnProductNameChanged();
           }
      }

Then when values from databound control editors are submitted to the server the the Web Forms Model Binding system will track whether any of these validation rules are violated in the page's ModelState property.

public void InsertProduct(Product p)
{
     if (ModelState.IsValid)
     {
           context.Products.InsertOnSubmit(p);
           context.SubmitChanges();
     }
}

To show any validation errors you could use asp:ValidationSummary control or asp:ModelErrorMessage:

<asp:ValidationSummary runat="server" ID="ValidationSummary1" />

Please note that even the model binding is a powerful feature included into the bound controls there are still some limitation.

Conclusion
With Model Binding support into our controls developing new application is never be as easy as it is now.  Please do not hesitate to download the RadControls for ASP.NET AJAX and try the model binding feature.



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