Binding ViewModel Property to ASP TextBox and Button - asp.net

This is my View
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="InsertUser.aspx.cs" Inherits="WebApplication1.InsertUser" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"></asp:ObjectDataSource>
<asp:TextBox></asp:TextBox> // i want to bind the Fullname Property here
<asp:Button></asp:Button> // i want to bind the Save() here
</div>
</form>
</body>
</html>
and i want to bind the property and method from my viewmodel. Is it possible?
this is my ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Services;
namespace Testing.ViewModel
{
public class UserVM
{
public int UserID { get; set; }
public string Fullname { get; set; }
[WebMethod]
public void Save()
{
}
}
}
can someone guide me to the right direction? i manage to bind the Grid with ObjectDataSource and i can perform CRUD operations but i cant manage to bind a View to a ViewModel.
this is my sample Binding from ViewModel with CRUD operation to my View with Grid
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title></head><body><form id="form1" runat="server">
<div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DataObjectTypeName="Testing.Model.User" DeleteMethod="DeleteUser" InsertMethod="CreateUser" SelectMethod="GetUsers" TypeName="Testing.ViewModel.UserListVM" UpdateMethod="UpdateUser"></asp:ObjectDataSource>
<asp:GridView ID="GridView1" DataSourceID="ObjectDataSource1" runat="server" AllowPaging="True" AutoGenerateColumns="False">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="Fullname" HeaderText="Fullname" SortExpression="Fullname" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
UserListVM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Testing.Model;
namespace Testing.ViewModel
{
public class UserListVM
{
public UserListVM()
{
}
public IEnumerable<User> GetUsers()
{
return VMIndex.Users;
}
public User UpdateUser(User user)
{
throw new NotImplementedException();
}
public User DeleteUser(User user)
{
throw new NotImplementedException();
}
public User CreateUser(User user)
{
throw new NotImplementedException();
}
}
}
Any help please.. Thanks in advance.

Related

.NET 4.5 Gridview with DropDownList in EditItemTemplate UpdateMethod

I have Gridview with list of ManufacturerTypes that is related with Manufacturers... So each ManufacturerType has a Manufacturer (2 tables -> 2 entities). When I want to update item ManufacturerType I wan`t to be possible to update Title from Entity ManufacturerType but also change the (Manufacturer) relation if the dropdownlist selectedvalue change.
<asp:GridView ID="gvManufacturerTypes" runat="server" DataKeyNames="manufacturerTypeId"
AutoGenerateColumns="false" GridLines="Vertical" CssClass="gridview"
CellPadding="4" ItemType="Entities.Models.ManufacturerType" SelectMethod="GetManufacturerTypesWithParams"
UpdateMethod="UpdateItem" DeleteMethod="DeleteItem"
AllowPaging="true" AllowSorting="true" PageSize="20" PagerSettings-FirstPageText="Prvi"
PagerSettings-LastPageText="Zadnji" PagerSettings-Mode="NumericFirstLast"
OnCallingDataMethods="gvManufacturerTypes_CallingDataMethods">
<Columns>
<asp:TemplateField HeaderText="Proizvajalec">
<ItemTemplate>
<asp:Label ID="lblManufacturer" Text='<%# Item.Manufacturer.Title %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlManufacturers" runat="server" ItemType="Entities.Models.Manufacturer" SelectMethod="GetManufacturers" SelectedValue='<%# Item.Manufacturer.ManufacturerId %>'
DataTextField="Title" DataValueField="manufacturerId" OnCallingDataMethods="ddlManufacturers_CallingDataMethods">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:DynamicField DataField="Title" />
<asp:CommandField ShowEditButton="true" EditText="Uredi" UpdateText="Shrani" CancelText="Prekliči" ItemStyle-Width="80" />
<asp:CommandField ShowDeleteButton="true" DeleteText="Izbriši" ItemStyle-Width="80" />
</Columns>
<PagerStyle CssClass="gridview_pager" />
</asp:GridView>
It generates me UpdateItem method and I change the load item and save changes sections like below:
// The id parameter name should match the DataKeyNames value set on the control
public void UpdateItem(int manufacturerTypeId, ModelMethodContext context)
{
ManufacturerType item = null;
// Load the item here
item = _manufacturerTypeRepository.GetAllWithRelations(m => m.Manufacturer)
.Where(x => x.ManufacturerTypeId == manufacturerTypeId).SingleOrDefault();
if (item == null)
{
// The item wasn't found
context.ModelState.AddModelError("", String.Format("Proizvajalec z idjem {0} ne obstaja.", manufacturerTypeId));
return;
}
context.TryUpdateModel(item);
if (context.ModelState.IsValid)
{
// Save changes here
_manufacturerTypeRepository.Save();
}
}
I also call the Include where I get the ManufacturerType entity with Include("Manufacturer") ... so I get the current ManufacturerType, and the TryUpdateModel method also change the Title of ManufacturerType (if I change it on edit in gridview), but Manufacturer always stays the same... I have also try to put the dropdownlist as control-parameter to UpdateMethod like
public void UpdateItem(int manufacturerTypeId, [Control] manufacturerId, ModelMethodContext context)
but it is always null... So I don`t know how to transfare value from dropdownlist to UpdateItem method (UpdateItem is not in codebehind of ManufacturerTypes.aspx but it is in busines logic layer) ManufacturerTypeBL.cs...
I didn`t find any solution for this that will use new features like ItemType in gridview and Select method and SelectMethod in dropdownlist etc...
Maybe I need to change the UpdateItem method with old fasioned way OnUpdating method and read the values from dropdown and lather call the busines logic layer with params?
EDIT - > add model classes (Manufacturer, ManufacturerType)
public class Manufacturer
{
[Key, ForeignKey("ManufacturerType")]
public int ManufacturerId { get; set; }
[StringLength(255)]
public string Title { get; set; }
public ManufacturerType ManufacturerType { get; set; }
}
public class ManufacturerType
{
[Key]
public int ManufacturerTypeId { get; set; }
[StringLength(50)]
public string Title { get; set; }
public Manufacturer Manufacturer { get; set; }
}
From what I can understand,
In the EditItemTempalte set SelectedValue='<%# Bind("ManufacturerId")%>'. i.e. Property name for the ManufacturerId in ManufacturerType Entity.
Also, it should not be required to fetch the relation (in the select query). If you fetch ManufacturerType item, and use correct property name in the EditTemplate controls, it should work fine.
If you can post your Model classes (Manufacturer and ManufacturerType) it will be more helpful to understand the issue.

Using DisplayForModel with MVC4 and the ASPX View Engine

Using ASP.NET MVC4 (.NET 4, C#) on MSVC 2010 SP1, I've noticed that I can pass a class model to a view using Razor and display the model using DisplayModelFor & EditorForModel but when I try to do the same using the ASPX view engine it doesn't work. Why is that? Code snippets from my test project below. Thanks.
My Controller:
namespace MvcApplication1.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
TestModelClass c = new TestModelClass();
c.MyInt = 999;
return View(c);
}
}
My Model:
namespace MvcApplication1.Models
{
public class TestModelClass
{
public int MyInt { get; set; }
}
}
My View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.TestModelClass>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<%Html.DisplayForModel(); %>
</div>
</body>
</html>
Alternate Razor (Works):
#model MvcApplication1.Models.TestModelClass
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DisplayForModel()
Successful output from Razor version:
Index
MyInt
999
You are missing a :.
The correct syntax should be
<%: Html.DisplayForModel() %>

How to Prevent Post back of Menu Control that is on Master Page in asp.net?

I have created Dynamic Menu from Database of SQLServer2008 which is loaded on page load and accordingly the menus are displayed. Problem is when i click any MenuItem of the menu from Content Page the Menu Control also loads again from the DataBase which i want to avoid the PostBack and prevent the Hit to DataBase for loading the menu.
In .master
<body>
<form runat="server">
<div class="page">
<div id="navbar" runat="server">
<asp:Menu ID="Menu1" Orientation="horizontal" RenderingMode="List" runat="server"
DynamicHorizontalOffset="0" OnMenuItemClick="Menu1_MenuItemClick">
<StaticMenuItemStyle HorizontalPadding="10px" />
</asp:Menu>
</div>
<br />
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
Content here....
</asp:ContentPlaceHolder>
</div>
</div>
<div class="footer">
</div>
</form>
</body>
In .master.cs file
public partial class SiteMaster : System.Web.UI.MasterPage
{
static string conStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
int empID = 0;
int recAffect = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateMenuItem();
}
}
}
populateMenuItem() is a method from where the Menu is Bind from SQLServerDB table called MenuMaster.
When i click any MenuItem the page is redirected. This works fine. Just i want to AVOID the LOADING OF MENU afte EACH LOADING OF CONTENT PAGE!
Help Appreciated!
Thanks in Advance!
What I do is once the application loads, I create the menu and load it into memory, and then query the data from memory instead. So I create a class like:
public class SiteMap
{
public string Name { get; set; }
public string Url { get; set; }
public List<SiteMap> Items { get; set; }
}
During the starting up of your application, query from database and build a collection of SiteMap objects, and store this in a static reference, like:
public static class SiteMapStore
{
private static List<SiteMap> _entries = null;
public static List<SiteMap> Entries
{
get { return _entries; }
set
{
if (_entries == value)
return;
lock(typeof(SiteMapStore))
{
if (_entries != value)
_entries = value;
}
}
}
}
Using the SiteMapStore, you can then always refer to this when building the menu. Storing the results in an object and globally will be much faster.

Reference masterpage variables from control in child page?

Is it possible to access Masterpage variables from a web user control that is in a child page? I know you can access them in child pages by adding the following
<%# MasterType VirtualPath="~/Master.master" %>
It doesn't seem to work when trying to access from a Web control that is inside a child page
User Controls essentially should be unaware of any pages outside the control. The better approach would be to have the control expose properties and events that the page itself (master page or normal) will use to set and retrieve values. Take this simple example:
class PassValueEventArgs : EventArgs
{
public string Value { get; set; }
}
public event EventHandler<PassValueEventArgs> RequestingValue;
public void ControlDoingWork()
{
PassValueEventArgs e = new PassValueEventArgs();
if (RequestingValue != null)
{
RequestingValue(this, e);
}
string fromHandlingPage = "Received " + e.Value + " from a handling page.";
}
Then whenever the user control should have a value, the page containing the user control can just handle the RequestingValue event and send the value to the user control. Otherwise just expose a public property of the user control, which you can even make databound, for an even easier solution.
Adding a complete example of the event-driven approach:
WebUserControl1EventArgs.cs
public class WebUserControl1EventArgs : EventArgs
{
public double ValueToSquare { get; set; }
}
WebUserControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplicationCS1_net20.WebUserControl1" %>
Text below will display "Nothing passed from parent page." if the event is unhandled,
else will display the square of the number passed if handled.<br /><br />
<asp:Label runat="server" ID="Label1" Font-Bold="true" Font-Size="Larger" Text="Nothing passed from parent page."></asp:Label>
WebUserControl1.ascx.cs
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public event EventHandler<WebUserControl1EventArgs> RequestingNumber;
protected void Page_Load(object sender, EventArgs e)
{
ControlDoingWork();
}
private void ControlDoingWork()
{
if (RequestingNumber != null)
{
WebUserControl1EventArgs e = new WebUserControl1EventArgs();
RequestingNumber(this, e);
Label1.Text = (e.ValueToSquare * e.ValueToSquare).ToString();
}
}
}
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplicationCS1_net20.WebForm1" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server"
OnRequestingNumber="WebUserControl11_RequestingNumber" />
</div>
</form>
</body>
</html>
WebForm1.aspx.cs
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void WebUserControl11_RequestingNumber(object sender, WebUserControl1EventArgs e)
{
e.ValueToSquare = 3.3;
}
}
WebForm2.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplicationCS1_net20.WebForm2" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</div>
</form>
</body>
</html>
WebForm2.aspx.cs
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Use the Page's Master property to access to it's masterpage. After that you can you FindControl method or use the master's public properties if it have any. For example in the master page code behind:
public Label Title { get { return lblTitle; } }

Custom elements in ASP.NET with custom child-elements

I know that it is possible to define custom tags in ASP.NET with User Controls. But as far as I know you can only add attributes to these controls. I would like to be able to embed more complex data, a bit lite this:
<myControls:MyGraph id="myGraph1" runat="server">
<colors>
<color>#abcdef</color>
<color>#123456</color>
</colors>
</myControls:MyGraph>
It this possible in ASP.NET? Should I try to extend a ListView? Or it there a better and more correct solution?
It is certainly possible. For your example the classes would look like:
[ParseChildren(true)]
class MyGraph : WebControl {
List<Color> _colors = new List<Color>();
[PersistenceMode(PersistenceMode.InnerProperty)]
public List<Color> Colors {
get { return _colors; }
}
}
class Color {
public string Value { get; set; }
}
And the actual markup would be:
<myControls:MyGraph id="myGraph1" runat="server">
<Colors>
<myControls:Color Value="#abcdef" />
<myControls:Color Value="#123456" />
</Colors>
</myControls:MyGraph>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
namespace ComponentDemo
{
[ParseChildren( true )]
public class MyGraph : System.Web.UI.WebControls.WebControl
{
private List<Color> _colors;
public MyGraph() : base() { ;}
[PersistenceMode( PersistenceMode.InnerProperty )]
public List<Color> Colors
{
get
{
if ( null == this._colors ) { this._colors = new List<Color>(); }
return _colors;
}
}
}
public class Color
{
public Color() : base() { ;}
public string Value { get; set; }
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ComponentDemo._Default" %>
<%# Register Assembly="ComponentDemo" Namespace="ComponentDemo" TagPrefix="my" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<my:MyGraph runat="server">
<Colors>
<my:Color Value="value1" />
<my:Color Value="value2" />
<my:Color Value="value3" />
<my:Color Value="value4" />
</Colors>
</my:MyGraph>
</div>
</form>
</body>
</html>
You cannot user UserControl for such purpoces. As adviced above, inherit Control or WebControl.

Resources