This article will show you how you can pass model value to partial
view on button click in you asp.net mvc
application. This article you can use in your MVC3, MVC4, and MVC5 application.
So for this article first we will create a new asp.net mvc
application and add a model class file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PartialViewInMvc.Models
{
public class ParticlaViewmodel
{
public
string PartialViewMessage { get; set; }
}
}
|
Now we will create a new controller file and add create view
file. After creating view file we will create partial view. For creating
partial view we will add we will right click on controller folder and right
click- > Add View. Please check the below screen shot.
Now we will create post method. After doing all the process
your code will look as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartialViewInMvc.Models;
namespace PartialViewInMvc.Controllers
{
public class HomeController
: Controller
{
//
// GET: /Home/
public
ActionResult Index()
{
ParticlaViewmodel
objparticlaviewmodel = new ParticlaViewmodel();
return
View(objparticlaviewmodel);
}
[HttpPost]
public
ActionResult Index(int id=0)
{
ParticlaViewmodel
objparticlaviewmodel = new ParticlaViewmodel();
objparticlaviewmodel.PartialViewMessage = "This
Value is passed form Model. Here are some country name India, Pakistan, Sri
Lanka.";
return
View(objparticlaviewmodel);
}
}
}
|
Now open your partial view and add the below code.
Partial view :
@model PartialViewInMvc.Models.ParticlaViewmodel
@{
<div>
<h2>@Model.PartialView1Message</h2>
</div>
}
|
Now add the below code in your main view where your want to
display the partialview on button click.
@model PartialViewInMvc.Models.ParticlaViewmodel
@{
ViewBag.Title = "Index";
}
@using
(Html.BeginForm("Index", "Home"))
{
<div>Load
Partial View :<input
type="submit"
value="Load
View" /></div>
<div style="border: 1px solid;">
@Html.Partial("PartialView",
new PartialViewInMvc.Models.ParticlaViewmodel { PartialViewMessage =
Model.PartialViewMessage })
</div>
}
|
Now run the application, and select the parameter and click
on Load view.
Now click on button your partial view will load.
DOWNLOAD
this code is not working :(
ReplyDeleteHi What issue your are facing?
Deletehow to display data from database using partial view?
ReplyDeleteHi You just needed to assign the value to model and rest you can refer from the above article,
Delete