Category Archives: MVC

Difference between Html.RenderPartial vs Html.Partial vs Html.RenderAction vs Html.Action in MVC

In this post, we are going to discuss about Html.RenderPartial vs Html.Partial, Html.RenderAction vs Html.Action. Let we split this stuff in two ways  based on binding the static and dynamic content like Render partial and Action Partial .

Partial Vs RenderPartial

  • @Html.Partial(“Details”)  –  returns a String as an output
  • @{ Html.RenderPartial(“Details”); } –  returns void as an output

Action Vs RenderAction

  • @Html.Action(“ActionName”, “ControllerName”) – returns a String as an output
  • @{ Html.RenderAction(“ActionName”, “ControllerName”); } –  returns void as an output

Render vs Action partial

Let us discuss about the main difference between RenderAction and RenderPartial. RenderPartial will render the view on the same controller. But RenderAction will execute the action method , then builds a model and returns a view result.

Render Partial : Use Html.Partial when you are rendering static content.

Action Partial : Use Html.Action when handling dynamic Content/data.

Where to use Html.Partial and Html.Action

Html.PartialIf we need to display a static menu for all users from the partial view, then we can use Render partial.

Example:

View : Here we call the partial view from the view (passing model as input).

@Html.Partial(“_partialName”, model)

Html.Action: If we need to display different menu items based on the user level, then we can use Action Partial.

Example:

Controller:

public ActionResult CustomerDetail() {
return PartialView(new CustomerDetailModel());
}

View

@model Model
@Html.Action(“CustomerDetail”)

Difference :

1) @Html.RenderPartial and @Html.RenderAction is the best practice to use in most cases because the output has been written in the same TextWriter object.

2) In contrast to this, @Html.Partial and @Html.Action methods create their own TextWriter instances at every time and buffer all their content into memory.

3) @Html.Action and @Html.RenderAction method is the best choice when you want to cache a partial view.
@Html.Partial and Html.RenderPartial method is the best choice when you want to load new view.

4) The return type for @Html.Partial and Html.Action returns string type values
@Html.RenderAction and Html.RenderPartial returns is void

5) @Html.Partial and @Html.Action will useful when assign the content into a variable for other purpose…

 

Have a cool coding………

 

Difference between return View() ,return Redirect() and return RedirectToAction() in MVC

return View() :

It commend to generate HTML to display for the required view and render/send it to the browser

Example :

public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
…….
};

return View(obj);
}

In this above code the view is  (it never call any controller) which is referring the Action Method.
This below also work like above

[HttpPost]
public ActionResult Index(string Name)
{
return MyIndex();
}

return Redirect()

It commend to redirect to specified URL instead of rendering HTML (ie., it redirect to new URL)

Example

[HttpPost]
public ActionResult Index(string Name)
{
return Redirect(“Home/TIndex”);
}

return RedirectToAction()

It commend to redirect to specified action instead of rendering HTML

Example

[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToAction(“TIndex”);
}

Note :

1)  Return View doesn’t make a new requests, it renders the view without changing URLs in the browser’s address bar. (ie., simple like Server.Transfer() )

2)  Return RedirectToAction makes a new requests and URL in the browser’s address bar is changed (ie., simple like Response.Redirect() )

RedirectToAction(“CustomerDetail”, “Customers”, new { CustomerID = 1001 })

In this above,it will generate the URL for you based on your route table.CustomerID will pass to the customerDetail action method under the CustomerFolder

3)  Redirect also work same as RedirectToAction , but you have to mention full URL to redirect

 

Different way to call controller from view using MVC Razor

Different way to call controller from view

Syntax    @Html.Action(“action”, “controller”, parameters)

Method : 1

@using (Html.BeginForm(“Save”,”ControllerName”, FormMethod.Post))
{
@Html.TextBoxFor(model => m.Name)
<input type=”submit” value=”Save” />
}

Note :

  •   “Save” be the name of the Html form. We can also use Ajax.BeginForm() instead of Html.BeginForm
  •    Html.BeginForm is nothing but Html form

Method : 2

From Jquery

1) var url = ‘@Url.Action(“ActionName”, “ControllerName”)’;
window.location = url;

2) $(this).load(“@Url.Action(“ActionName”, “ControllerName”)”);

Note :

  •  2nd way is used for loading the partialview to the mainview

Method : 3

@Html.ActionLink(“ActionLinkName”, “ActionName”, “ControllerName”)

 

 

 

How to use WebGrid from PartialView using Razor

WebGrid is used to display the data with paging and sorting. In this article, we will discuss about how to load the data to webgrid and would like to explore how can to use default paging and sorting.

Controller

Let we create simple controller which will return the UserDetailModel to the view. From the view we can bind the WebGrid using the model data.

public ActionResult LoadGridinPartialView()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  "INDIA" },
new Country() { CountryId = 2, CountryName= "US" },
new Country() { CountryId = 3, CountryName= "Russia" },
new Country() { CountryId = 4, CountryName= "UK" }
};
return View(obj);
}

View

From the below code, just passing the model data to the partial view for loading WebGrid.

@model RegistrationForm.Models.UserDetailModel
@{
ViewBag.Title = "Load WebGrid in Partial View";
}
<h2>Load Grid in Partial View</h2>
@{
Html.RenderPartial("_LoadGrid", Model.CountryDetail);
}

Note :

   From Html.RenderPartial(“_LoadGrid”, Model.CountryDetail);

  •    _LoadGrid being created under the “Shared” folder
  •    Model.CountryDetail is model information being passed as parameter to the partial view

PartialView (_LoadGrid)

_LoadGrid Partial view bind the WebGrid by receiving model data from the view.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_LoadGrid</title>
</head>
<body>
<div>
@{

var grid = new WebGrid(source: Model, rowsPerPage: 3, canPage: true, canSort: true);
<div id="grvCountry">
@grid.GetHtml(
fillEmptyRows: false,mode: WebGridPagerModes.All,
htmlAttributes: "width:100%",firstText: "<< First",
previousText: "< Prev",nextText: "Next >",
lastText: "Last  >>",
columns: new
[] { grid.Column("CountryId", header: "Country ID"), grid.Column("CountryName", header: "Country Name") } ) </div> } </div> </body> </html>

OUTPUT

LoadGridinPartialView

How to create simple WebGrid in MVC (Razor engine)

Create simple WebGrid in MVC (Razor engine)

Controller

public class WebGridExampleController : Controller
{
public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  “INDIA” },
new Country() { CountryId = 2, CountryName= “US” },
new Country() { CountryId = 3, CountryName= “Russia” },
new Country() { CountryId = 4, CountryName= “UK” }
};

return View(obj);
}
}

View

@model RegistrationForm.Models.UserDetailModel
@{
ViewBag.Title = “Index”;
}
<style type=”text/css”>
th
{
font-size: 14px;
font-weight: normal;
color: #039;
padding: 10px 8px;
}
table
{
font-family: arial,sans-serif;
font-size: 11px;
border-width: 1px;
border-color: black;
}
table th
{
background: #D3D3D3;
border-width: 1px;
border-style: solid;
border-color: black;
}
table td
{
background: #AFEEEE;
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: black;
}
.foot
{
text-align: center;
}
</style>
<h2>
Country Details</h2>
@{

var grid = new WebGrid(source: Model.CountryDetail, rowsPerPage: 3, canPage: true, canSort: true);

<div id=”grvCountry”>
@grid.GetHtml(
fillEmptyRows: false, mode: WebGridPagerModes.All,
htmlAttributes: “width:100%”, firstText: “<< First”,
previousText: “< Prev”, nextText: “Next >”,  lastText: “Last  >>”,
columns: new

[]
{  grid.Column(“CountryId”, header: “Country ID”, style: “column1”),
grid.Column(“CountryName”, header: “Country Name”, style: “column2”),
   })
</div>
}

Output :

Explanation:

      In first line(var grid…), we are assigning the mode,
rowperpage : how many rows want to display in Webgrid,
canpage : here want to set the default pagination in the webgrid to be true/false
canSort  : here want to set filter based on the column header (true/false)

Model.CountryDetail : Here being binding the other class inside the UserDetailModel model…

Getting Selected text/value using jquery in MVC Razor

In this post, we are going to discuss how to get the drop down selected value using Asp.Net MVC razor and jquery.

Model :

A simple Model which has Country ID, Country Name and SelectedCounty.

public class UserDetailModel
{
[Display(Name = “CountryDetail”)] public List<Country> CountryDetail;
[Display(Name = “selectedcountry”)]
public string SelectedCountry { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}

Controller :

Here we creating a collection which contain the list of countries for binding in the drop down list.

public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  “INDIA” },
new Country() { CountryId = 2, CountryName= “US” },
new Country() { CountryId = 3, CountryName= “Russia” },
new Country() { CountryId = 4, CountryName= “UK” }
};
return View(obj);
}

[HttpPost]
public void Save(FormCollection form, string selectedCountry)
{
}

View

A simple view which consist of Asp .Net MVC razor drop down list.  This drop down bind the mode which has return from the above view.

@Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail, “CountryId”, “CountryName”)

Method 1: (Getting value using JQuery Selector)

<script type=”text/javascript”>
$(document).ready(function() {
$(“select[id^=’SelectedCountry’]”).change(function() {
alert($(‘option:selected’, $(this)).text());
});
});
</script>

Method 2: (Getting value using JQuery Onchange)

@Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail,
“CountryId”, “CountryName”),new{onchange = “ddListChange()”  })

<script type=”text/javascript”>
function ddListChange()
{
alert($(‘#SelectedCountry option:selected’).text());
}
</script>

Output

MVC Razor : How to get the value of Html.DropDownListFor using controller

In this post, we are going the discuss about how to get the value from the Html. DropDownListFor razor control using a controller.

View

@using (Html.BeginForm("Save", "userdetail", FormMethod.Post, new { @id = "validationlist" }))
{
@Html.DropDownListFor(model => model.SelectedCountry, new SelectList

(Model.CountryDetail.OrderBy(s => s.CountryName), "CountryId", "CountryName",  Model.SelectedCountry), "-- Select Country --")
<input id="submit" type="submit" name="Submit" value="Submit" />
}

Model :

public class UserDetailModel
{
Display(Name = "CountryDetail")]
public List<Country> CountryDetail;

[Display(Name = "selectedcountry")]
public string SelectedCountry { get; set; }
}
public class Country
{
public int CountryId { get; set; }

public string CountryName { get; set; }
}

Controller :

public ActionResult Index()
{
UserDetailModel obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  "INDIA" },
new Country() { CountryId = 2, CountryName= "US" },
new Country() { CountryId = 3, CountryName= "Russia" },
new Country() { CountryId = 4, CountryName= "UK" }
};

return View(obj);
}

[HttpPost]
public void Save(FormCollection form, string selectedCountry)
{

}

OutPut

[

How to use cascading DropDown in MVC Razor

How to use cascading DropDown in MVC Razor

Model

namespace RegistrationForm.Models
{
public class UserDetailModel
{
[Display(Name = "CountryDetail")] public List<Country> CountryDetail; [Display(Name = "selectedcountry")] public string SelectedCountry { get; set; } [Display(Name = "stateDetail")] public List<State> StateDetail { get; set; } } public class Country { public int CountryId { get; set; } public string CountryName { get; set; } } public class State { public int StateId { get; set; } public string StateName { get; set; } } }

Controller:

public class GettingTextInDDLController : Controller
{
public ActionResult Index()
{
var obj = new UserDetailModel();
obj.CountryDetail = new List<Country>()
{
new Country() { CountryId = 1, CountryName =  "INDIA" },
new Country() { CountryId = 2, CountryName= "US" },
new Country() { CountryId = 3, CountryName= "Russia" },
new Country() { CountryId = 4, CountryName= "UK" }
};

return View(obj);
}
public ActionResult FirstDdl(string selectedCountry)
{
var obj = new UserDetailModel();
if (selectedCountry == "INDIA")
{
obj.StateDetail = new List<State>()
{
new State() {StateId = 1, StateName = "Tamil Nadu"},
new State() {StateId = 2, StateName = "Karnataka"},
new State() {StateId = 3, StateName = "Delhi"},
new State() {StateId = 4, StateName = "J&K"}

};
}
else
{
//.... Bind states for other countries
obj.StateDetail = new List<State>()
{
new State() {StateId = 1, StateName = "Others"},
};
}

return Json(obj);
}
}

View  

use @model RegistrationForm.Models.UserDetailModel in the first line of view

<script type="text/javascript">
function ddListChange() {
$.ajax({
url: '@Url.Action("FirstDdl", "GettingTextInDDL")',
data: { selectedCountry: $('#SelectedCountry option:selected').text() },
cache: false,
type: "POST",
success: function (data) {
var parsedJsonData = data.StateDetail.length;
var state = "<option value=`0`>Select City</option>";
for (var x = 0; x < parsedJsonData; x++) {
state += "<option value=" + data.StateDetail[x]["StateId"] + ">" + data.StateDetail[x]["StateName"] + "</option>";
}
$('#ddlstate').html(state).show();
},
error: function (reponse) { alert("error : " + reponse); }
});
}
</script>

<table>
<tr>
<td id="tdcountry">
@Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail, "CountryId", "CountryName"),
new
{
onchange = "ddListChange()"
})
</td>
</tr>
<tr>
<td id="tdstate">
<select id="ddlstate" name="ddlstate" style="width: 200px">
<option>Select Country</option>
</select>
</td>
</tr>
</table>

Output

Before Selecting Country:

After Selecting it will populate list of states belong to Country India

Confirmation message after clicking the ActionLink in MVC

In many scenario, it necessary to pop up the confirm alert box while deleting ,saving and editing  information in Asp .Net MVC application. So let us discuss about how can we achieve using JQuery code .

Controller

Create simple controller and generating view based on the controller as shown below.

View (index)

As shown below code, we had created ConfirmationDialog function using javascript to show the popup with alert message. Next creating a AcionLink control which will show the popup by calling the javascript method in the onclick event.

<script type="text/javascript">
function ConfirmationDialog() {
if(confirm("Are you sure to continue?"))
return true;
else
return false;
}
</script>

@Html.ActionLink("Click to Confirm", "Confirmation", null, new { onclick = "return ConfirmationDialog()" })

OUTPUT:

If you click ok, it will redirect to the Confirmation view

store array in viewbag and retrieving in the view

In this post, we will discuss about how to store the array in view bag and how to use them in view.

Controller

A simple Controller action which store the string array in the ViewBag and return to the view.

public ActionResult Index()
{
string[] Countries = {“India”, “US”,”Nepal” };
ViewBag.Countries = Countries;
return View();
}

View

<h2>List Of Cities</h2>
@foreach (string city in ViewBag.Countries) {
<li>@city
</li>
}

OUTPUT :