How to show two Partials view data on Index.cshtml MVC3? - asp.net-mvc

I have created a web application in mvc3 and created two partial views
one having controls two dropdownlist.
second having webgrid which shows data from database.
partialview1.cshtml
#model Mapping.Models.SecurityIdentifierMapping
#using (Html.BeginForm("Mapping", "Home"))
{
#Html.DropDownList("SecurityID", Model.PricingSecurityID, "-- Select SecurityID --")
<br />
#Html.DropDownList("CUSIPID", Model.PricingSecurityID, "-- Select CUSIPID --")
<br />
<button type="submit">Map</button>
}
partialview2.cshtml
#model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
#{
ViewBag.Title = "Mapping";
WebGrid grid = null;
if (Model.Count() > 0 ){
grid = new WebGrid(source: Model,
defaultSort: "Id",
canPage: true,
canSort: true,
rowsPerPage:20);
}
}
<h2>Mapping</h2>
#if (grid != null)
{
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("", header: null, format: #<text>#Html.ActionLink("Edit", "Edit", new { id = (int)item.id }) #Html.ActionLink("Delete", "Delete", new { id = (int)item.id })</text>),
grid.Column("PricingSecurityID"),
grid.Column("CUSIP")
)
)
}
<br />
<p>
#Html.ActionLink("Back", "Index")
</p>
in index.cshtml
<div>
#Html.Partial("_ControlsPartial",)
</div>
<div>
#Html.Partial("_WebGridPartial")
</div>
inside Indexcontroller.cs in Index()
public ActionResult Index()
{
//FOR POPULATE DROPDOWN
//SecurityIdentifierMapping objModel = new SecurityIdentifierMapping();
//objModel.PricingSecurityID = objRepository.GetPricingSecurityID();
//objModel.CUSIP = objRepository.GetCUSIP();
//return View(objModel);
//FOR DISPLAY DATA IN WEBGRID
return View(dbContext.SecurityIdentifierMappings);
}
here problem is webgrid partial view is having#model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
and
controlpartilview is having #model Mapping.Models.SecurityIdentifierMapping
so HOW CAN I CREATE A VIEWMODEL.cs A NEW CLASS WHICH WILL HAVE BOTH MODELS AND HOW CAN I WRITE IT IN INDEX(() SO THAT THAT METHOD WILL POPULATE DROPDOWN ALSO AND SHOW DATA IN WEBGRID ALSO ?

Why not just create a custom View Model class that contains two properties:
public class SecurityIdentifierMappingViewModel
{
public IEnumerable<SecurityIdentifierMapping> MappingList {get; set; }
public SecurityIdentifierMapping Mapping {get; set; }
}
Then you can pass this custom view model to the Index view and the corresponding property as the view model of each of the partials
EDIT
Your Index action would then look something like this:
public ActionResult Index()
{
// single mapping
var mapping = new SecurityIdentifierMapping();
maping.PricingSecurityID = objRepository.GetPricingSecurityID();
mapping.CUSIP = objRepository.GetCUSIP();
var viewModel = new SecurityIdentifierMappingViewModel
{
Mapping = mapping,
MappingList = dbContext.SecurityIdentifierMappings.ToList()
};
return View(viewModel);
}
And in Index.cshtml:
#model SecurityIdentifierMappingViewModel
<div>
#Html.Partial("_ControlsPartial", Model.Mapping)
</div>
<div>
#Html.Partial("_WebGridPartial", Model.MappingList)
</div>

Related

how to use linq for showing image in webgrid [duplicate]

in web-grid i can not use navigation properties between my classes(products and productimages classes). for example i have used below code in web grid:
grid.Column("", "test",item=> (item.ProductImages.First().Id)+(item.Price))
but i got error:
'System.Collections.Generic.HashSet<WebStore.Models.ProductImage>' does not contain a definition for 'First'
my total code is like below:
#model IEnumerable<WebStore.Models.Product>
#using System.Linq;
#{
var grid = new WebGrid(source: Model, rowsPerPage: 5,ajaxUpdateContainerId:"divGrid");
}
#grid.GetHtml(tableStyle: "gridStyle", headerStyle: "gridHeader", rowStyle: "gridRow", alternatingRowStyle: null,htmlAttributes:new{Id="divGrid"},
columns: new WebGridColumn[] {
grid.Column("ProductName", "Product Name"),
grid.Column("Price", "Price"),
grid.Column("Description", "Description"),
grid.Column("CategoryName","Category Name",x=>x.Category.CategoryName),
grid.Column("", "test",item=> (item.ProductImages.First().Id)+(item.Price)),
grid.Column("","",x=>Html.ActionLink("Edit", "Edit", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Details", "Details", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Delete", "Delete", new{id=x.Id}))
}
)
this is my index view:
#model IEnumerable<WebStore.Models.Product>
#using System.Linq
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutCategory.cshtml";
}
<br/>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div id="divGrid">
#{ Html.RenderPartial("_ProductTitle", Model); }
</div>
this is my RenderPartial that use web grid before i posted:
#model IEnumerable<WebStore.Models.Product>
#using System.Linq
#ViewBag.test
#{
var grid = new WebGrid(source: Model, rowsPerPage: 5,ajaxUpdateContainerId:"divGrid");
}
#grid.GetHtml(tableStyle: "gridStyle", headerStyle: "gridHeader", rowStyle: "gridRow", alternatingRowStyle: null,htmlAttributes:new{Id="divGrid"},
columns: new WebGridColumn[] {
grid.Column("ProductName", "Product Name"),
grid.Column("Price", "Price"),
grid.Column("Description", "Description"),
grid.Column("CategoryName","Category Name",x=>x.Category.CategoryName),
grid.Column("", "test",item=>(int) (item.ProductImages.FirstOrDefault().Id)+(int)(item.Price)),
grid.Column("","",x=>Html.ActionLink("Edit", "Edit", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Details", "Details", new{id=x.Id})),
grid.Column("","",x=>Html.ActionLink("Delete", "Delete", new{id=x.Id}))
}
)
It's because definition of First is available in System.Linq. So, you should have System.Linq in your razor page :
#using System.Linq;
if you are using Linq in multiple page, you can add System.Linq namespace in web.config so that you do not need to write above using in each page. You can add namespace in web.config in following configuration :
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="System.Linq" />
</namespaces>
</pages>
</system.web.webPages.razor>
i got the answer of my question with below code from the net:
I followed your steps and test your code and the same error display. So I think the format in your code can not be used in webgrid. So I think about another way to meet your requirement: we need a ViewModel to display what you want to show in the View and search the first item in Controller then save as ViewModel and pass the ViewModel to View, then we do not need search in the View. Here I will show you the steps with my demo.
Now, we have two model Product and Quantity that one product has many quantities. We should create a ViewModel.
ViewModel.cs:
public class ViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public long quan { get; set; }
}
We can initialize some data and search the first value of Quantity depend on Product in Controller and assign to the ViewModel.
InventoryController .cs:
public class InventoryController : Controller
public ActionResult WebgridSample()
{
ObservableCollection<Product> inventoryList =
new ObservableCollection<Product>();
inventoryList.Add(new Product
{
Id = "P101",
Name = "Computer",
Description = "All type of computers",
quantity = new List<Quantity>
{
new Quantity {QUAN = 100 },
new Quantity {QUAN = 200 },
new Quantity {QUAN = 300 }
}
});
inventoryList.Add(new Product
{
Id = "P102",
Name = "Laptop",
Description = "All models of Laptops",
quantity = new List<Quantity>
{
new Quantity {QUAN = 400 },
new Quantity {QUAN = 500 },
new Quantity {QUAN = 600 }
},
});
inventoryList.Add(new Product
{
Id = "P103",
Name = "Camera",
Description = "Hd cameras",
quantity = new List<Quantity>
{
new Quantity {QUAN = 700 },
new Quantity {QUAN = 800 },
new Quantity {QUAN = 900 }
}
});
IEnumerable<string> model = (from sig in inventoryList
select new ViewModel
{
Name = sig.Name,
Description = sig.Description,
quan = sig.quantity.FirstOrDefault(),
}).ToList();
return View(model);
}
We can call each parameters of ViewModel in webgrid without using First().
WebgridSample.cshtml:
<div id="gridContent">
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("Id", ),
grid.Column("Name", " Name"),
grid.Column("Description", "Description", style: "description"),
grid.Column("Quantity", "quan "</i>)
))

how to insert the selected value from DDL to DB by MVC Razor

hi I have MVC Razor application as e catalog and I used drop down-list to bind data from DB but the DDl bind the same value from DB as if I have three categories " x , Y , Z" the DDL returned similar values " Z ,Z , Z ".As it have the last value "y" . also I tried to insert the selected value "ID" to DB when user selected the item from DDL but I couldn't and it returned false selected value.
public class CategoryController : Controller
{
private AndriodContext db = new AndriodContext();
List<SelectListItem> items = new List<SelectListItem>();
List<string> category = new List<string>();
SelectListItem s = new SelectListItem();
//
// GET: /Category/
public ActionResult Index()
{
var x = db.Categories.Where(y => y.Active == true).ToList();
return View(x);
}
public ActionResult Create()
{
var data = db.Categories.ToList().Distinct();
List<string> x = new List<string>();
foreach (var t in data)
{
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
}
ViewBag.Parent = items;
return View();
}
//
// POST: /Category/Create
[HttpPost]
public ActionResult Create(Category category, IEnumerable<HttpPostedFileBase> files)
{
var data = db.Categories.ToList().Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in data)
{
SelectListItem s = new SelectListItem();
s.Text = t.Name;
s.Value = t.Cat_ID.ToString();
items.Add(s);
if (s.Selected)
{ category.Parent_ID = int.Parse(s.Value); }
}
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
}
#using (Html.BeginForm("Create", "Category", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-field create-Bt3">
#Html.DropDownList("Parent", new SelectList(ViewBag.Parent, "Value", "Text"), "- Select Parent -")
</div>
<div>
<p class="create-Bt ">
<input type="submit" value="Create" />
</p>
</div>
<br />
<br />
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</fieldset>
}
you need to import jquery 1.7.1.min.js(DOM) in viewpage :
get the jquery DOM from jquery website(http://blog.jquery.com/2011/11/21/jquery-1-7-1-released/).
then in button click (<input type="submit" value="Create" onclick="GetDropDownValue();"/>) :
wrote a javascript function :
<script type="text/javascript" language="javascript">
function GetDropDownValue()
{
$("#hdnParentId").val($("#Parent").val());
}
</script>
The best practice to use a model to bind the dropdownlist instead of ViewBag.
If you don't want to use model the you can do one trick.
you put a hidden field(<input type="hidden" name="hdnParent" id="hdnParentId" />) in view page and calculate selected value of dropdownlis by simple jquery using :
$("#Parent").val();.
make the dropdownlist :
#Html.DropDownList("Parent", new SelectList(ViewBag.Parent, "Value", "Text"), "- Select Parent -",new{ id="Parent" });
After that you get a string parameter in HTTPPOST in controller :
[HttpPost]
public ActionResult Create(string hdnParent) //hdnParent is the name of dropdownlist
{
//now you can get the seleced value from "hdnParent".
//do the stuffs
return View();
}

The model item passed into the dictionary is of type 'requires a model item of type 'System.Collections.Generic.IEnumerable`

I have created a web application in mvc3 and created two partial views
one having controls like dropdownlist.
second having webgrid which shows data from database.
partialview1.cshtml
#model Mapping.Models.SecurityIdentifierMapping
#using (Html.BeginForm("Mapping", "Home"))
{
#Html.DropDownList("SecurityID", Model.PricingSecurityID, "-- Select SecurityID --")
<br />
#Html.DropDownList("CUSIPID", Model.PricingSecurityID, "-- Select CUSIPID --")
<br />
<button type="submit">Map</button>
}
partialview2.cshtml
#model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
#{
ViewBag.Title = "Mapping";
WebGrid grid = null;
if (Model.Count() > 0 ){
grid = new WebGrid(source: Model,
defaultSort: "Id",
canPage: true,
canSort: true,
rowsPerPage:20);
}
}
<h2>Mapping</h2>
#if (grid != null)
{
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("", header: null, format: #<text>#Html.ActionLink("Edit", "Edit", new { id = (int)item.id }) #Html.ActionLink("Delete", "Delete", new { id = (int)item.id })</text>),
grid.Column("PricingSecurityID"),
grid.Column("CUSIP")
)
)
}
<br />
<p>
#Html.ActionLink("Back", "Index")
</p>
in index.cshtml
<div>
#Html.Partial("_ControlsPartial",)
</div>
<div>
#Html.Partial("_WebGridPartial")
</div>
HomeController.cs
public ActionResult Index()
{
SecurityIdentifierMapping objModel = new SecurityIdentifierMapping();
objModel.PricingSecurityID = objRepository.GetPricingSecurityID();
objModel.CUSIP = objRepository.GetCUSIP();
return View(objModel);
}
How can i show webgrid and populate dropdown with same Index()??
getting error :(
what should be 2nd parameter inside #Html.Partial() so that both grid and control works fine on same page.?
You are passing a SecurityIdentifierMapping model to the Index view. Inside this Index view you are calling 2 partials:
#Html.Partial("_ControlsPartial")
and:
#Html.Partial("_WebGridPartial")
The first one works fine because it is strongly typed to SecurityIdentifierMapping but the second one (the one with the grid) doesn't work because it is strongly typed to IEnumerable<SecurityIdentifierMapping>. Thus the exception you are getting.
I would recommend you using a view model which will contain 2 properties: one simple SecurityIdentifierMapping that you could pass to the first partial and an IEnumerable<SecurityIdentifierMapping> property that you will pass to the second partial. It is the controller action that will fill this view model and pass it to the Index view:
Index.cshtml:
#model MyViewModel
<div>
#Html.Partial("_ControlsPartial", Model.SecurityIdentifier)
</div>
<div>
#Html.Partial("_WebGridPartial", Model.Identifiers)
</div>

Change value of grid item

I have table:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Add</legend>
<br />
#{
var grid = new WebGrid(ViewBag.produkty,null, "names", 5);
}
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("name"),
grid.Column("value"),
grid.Column(header: "Add", format: (item) =>
new HtmlString(
Html.TextBoxFor(model => model.add).ToString())),
grid.Column( header: "Ok", format: (item) =>
new HtmlString(
Html.ActionLink("OK", "add_method", new { ID_name = item.ID_name }).ToString()))
)
)
</fieldset>
}
Controller:
public ActionResult use()
{
var nam = (from d in baza.Names
select new { d.ID_name, d.name, d.value}).ToList();
ViewBag.names= nam;
return View();
}
public ActionResult add_method(int ID_name, useModel use)
{
Use us = new Use();
var dat = DateTime.Today;
us.value = use.add;
us.ID_Name= ID_name;
us.data = dat;
baza.Zuzycies.InsertOnSubmit(us);
baza.SubmitChanges();
return RedirectToAction("use", "Product");
}
Model:
public class useModel
{
public int ID_name{ get; set; }
public decimal value{get;set;}
public string date { get; set; }
}
So, I have list of product on page. And I want to add a value (amount of product) into TextBox and press a ActionLink "OK" next to the textbox. How can I get amount of product in add_method? Or how insert submit button next to every one product (instead ActionLink "OK"), then is enought make use POST method...
You can use a grid componet with built-in edits functions (like the telerik Grid).
I think it's better to use ajax not reagular post request for your scenario.
Or you can do that ajax calls to the server with jquery, just send the parameters to the controller.

using a usercontrol on aspx page in MVC using partial view

I have Dropdown and on click of a button, I want to display data in the usercontrol
the below code is not working as expected.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%
using (Html.BeginForm())
{%>
<%=Html.DropDownList("CarMake", (SelectList)ViewData["CarMake"])%>
<input type="submit" value="Get all car model" />
<%
Html.RenderPartial("CarModel");
} %>
</asp:Content>
// in controller
public ActionResult Test1()
{
ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test1(int carMake)
{
ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
var carModel = _carDataContext.Models.Where(m => m.MakeId == carMake).ToList();
return PartialView("CarModel", carModel);
}
Since you're doing a full post of the form, you don't want to return a partial view. You want to set the ViewData["CarModel"] to the correct model, then re-render the same view. The RenderPartial in the view will use this to "include" the correct partial view in the code.
Note this would be different if you were posting via AJAX. At that point, you'd have it set up to replace a particular element of the page and you would want to only render the partial that goes into that element.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test1(int carMake)
{
ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
ViewData["CarModel"] = _carDataContext.Models.Where(m => m.MakeId == carMake).ToList();
return View();
}

Resources