how to generate new row in webgrid on asp.net mvc4 - asp.net-mvc

I am having Text Box and a Button.I need to add Text Box value in Web grid when button was clicked.I coded to add text box value in grid but in the same column cell the value will be updated. I need to generate new column and add values ...
Index.cshtml Code
#{
#Html.TextBox("Value", "", new { id = "txtid" })
<input type="button" value="Submit" onclick="onSelectedIndexChanged()" id="btn" />
WebGrid grid = new WebGrid(Model, selectionFieldName: "SelectedRow");
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Edit", header: null, format: #<text>#item.GetSelectLink("Edit")</text>),
grid.Column("Firstname", format: #<text>#item.GivenName</text>),
grid.Column("Surname", format: #<text>#item.Surname</text>),
grid.Column("Age", format: #<text>#item.Age</text>)
)
)
}
Models Code:
People.cs
public ObservableCollection<People> GetCustomerList(string firstname)
{
ObservableCollection<People> CustomerList = new ObservableCollection<People>();
DataTable dtCustomer = new DataTable();
CustomerList.Add(new People { Id = i, GivenName = firstname, Surname = "Kumar", Age = 25 });
i++;
return CustomerList;
}
Controller Code:
Home Controller.cs
public ActionResult GetPeople(string firstname)
{
//List<People> ItemList = new List<People>();
// ViewBag.Items = ItemList;
ObservableCollection<People> ItemList = new ObservableCollection<People>();
People Customer = new Models.People();
ItemList = Customer.GetCustomerList(firstname);
return PartialView("Index", ItemList);
}

Related

Webgrid Drop down Save or Update

I started using web grid from last couple of days. Everything was so handy with webgrid like displaying columns with different datatype like textbox, label, drop down etc. But how do I save data or update data.
I tried using action link and submit buttons but none of them worked for me. They weren't fetching the modified drop down data in my controller. The action link was able to fetch the user id but it couldn't get the changed drop down value.
Below is the code:
View
WebGridColumn colLocation = null;
foreach (var col in Model)
{
colLocation = new WebGridColumn()
{
Header = "Locations",
Format = (item) => #Html.DropDownList("LocationId", #col.LocationItems.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
}
)
)
};
colSave = new WebGridColumn()
{
Header = "Save User",
Format = (item) => Html.ActionLink("Save", "Save", "UsersList", new { userId = item.UserId, locationId = item.LocationId }, new { #class = "btn btn-default" }),
CanSort = true
};
}
columns.Add(colLocation);
columns.Add(colSave);
#grid.GetHtml(tableStyle: "webgrid",
headerStyle: "header",
selectedRowStyle: "select",
alternatingRowStyle: "alt",
columns: columns
)
Controller
public ActionResult Save(int userId, int locationId)
{
var user = Utility.SetUserDetails(userId, locationId);
return RedirectToAction("UsersList");
}
After some rigorous trials, I've achieved this functionality. This can be done using ajax.
I've to extend my column properties to include class & id attribute
colUser = new WebGridColumn()
{
Header = "User Id",
ColumnName = "UserId",
CanSort = true,
Format = #<text>
<span class="display"><label id="lblUserId">#item.UserId</label></span>
<input type="text" id="inUserId" value="#item.UserId" class="edit" style="visibility:hidden" />
</text>
};
colLocation = new WebGridColumn()
{
Header = "Locations",
Format = #<text>
#Html.DropDownList("Location", #col.LocationItems.Select(l => new SelectListItem
{
Text = l.Text,
Value = l.Value,
Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
}
), new { #class = "edit", #id = "inLocation" })
</text>
};
colSave = new WebGridColumn()
{
Header = "Save User",
Format = #<text>
Save
</text>
};
After adding the jquery script, we can post the selected values into controller,
<script type="text/javascript">
$(function () {
$('.save-btn').on("click", function () {
var tr = $(this).parents('tr:first');
var id = tr.find("#inUserId").val();
var location = tr.find("#inLocation").val();
var User =
{
"UserId": id,
"LocationId": location
};
$.ajax({
url: '/UsersList/SaveData/',
data: JSON.stringify(User),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
isSuccess = result;
},
error: function (result) {
isSuccess = result;
}
})
});
});
</script>
In the controller, add new method,
public ActionResult SaveData(UserAccountViewModel User)
{
int userId = User.UserId;
int locationId = Convert.ToInt32(User.LocationId);
var user = Utility.SetUserDetails(userId, locationId);
return RedirectToAction("UsersList");
}

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>)
))

returning data from controller to VIEW

ii am told to create a login system in MVC 3 using old traditional sql queries etc, i have created login but problem is that i'm returning data from model to View . I have created datatable in model and returning it to controller, successfully but don't know that how to show that data on view ? have searched good but didn't help.
MODEL :
public ConnectionStatus Login_db(String email, String pwd, String conStr)
{
String hashedpwd_login = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "SHA1");
using (SqlConnection sqlCon = new SqlConnection(conStr))
{
using (SqlCommand sqlCom = new SqlCommand())
{
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "select Count(*) from tblRegister where userEmail=#email AND userPwd=#pwd";
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", hashedpwd_login);
String select_com = "select * from tblRegister";
SqlCommand sqlCom2 = new SqlCommand(select_com, sqlCon);
ConnectionStatus connectStatus = new ConnectionStatus();
int no_rows_affected;
SqlDataAdapter sda = new SqlDataAdapter(select_com, sqlCon);
DataTable data_tb = new DataTable();
try
{
sqlCon.Open();
no_rows_affected = Convert.ToInt32(sqlCom.ExecuteScalar());
if (no_rows_affected == 1)
{
connectStatus.Message = "User logged in successfully, " + no_rows_affected;
sda.Fill(data_tb);
tableCreation tb_creation = new tableCreation();
tb_creation.CreateTable = data_tb;
}
else
{
connectStatus.Message = "Invalid email/password combination.";
}
}
catch (Exception ex)
{
connectStatus.Message = ex.Message;
}
return connectStatus;
}
}
}
Controller :
public ActionResult loginResult(String command, FormCollection formData)
{
if (command == "Login")
{
var email = formData["txtboxEmail"];
var pwd = formData["txtboxPassword"];
// String conStr = "Data Source=HUNAIN-PC;Initial Catalog=registration;User ID=sa;Password=abc123!##";
database model_db = new database();
var db_status = model_db.Login_db(email, pwd, conStr);
ViewBag.Message = db_status.Message;
}
tableCreation retTable = new tableCreation();
return View(retTable.CreateTable);
}
View:
#{
ViewBag.Title = "Login Authentication";
}
<h2>Login Authentication</h2>
<h4>#ViewBag.Message</h4>
Note: some classes are user defined for multi purposes.
You can use WebGrid in MVC3. This is new in MVC3. Use this code in your View.
#model IList<YourViewModel>
#{
ViewBag.Title = "Login Information";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{
var grid = new WebGrid(source: Model, rowsPerPage: 200,
canPage: false, canSort: true, defaultSort: "Absentee");
}
<p>
<h2>Absentee List</h2>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column(format: (item) => Html.ActionLink("Edit", "Edit",
new { id = item.Id })),
grid.Column("Absentee", "Absentee",canSort:true),
grid.Column("AbsStart", "AbsStartDate")
))
</div>
</p>

Object reference not set to an instance of an object for dropdownlist in model

I have no idea why this is happening, I have set the values and debugged it, but it is just not passing the information from the controller to the view. Here is what is going on
Model:
public class QueueFilterModel
{
public string SelectedFilter { get; set; }
public string query { get; set; }
public List<string> MyFilterList { get; set; }
}
Controller:
[HttpGet]
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View();
}
View:
#model RazorARPP.Models.QueueFilterModel
#{
ViewBag.Title = "Queue";
}
<h2>Queue</h2>
<form action="" method="post" enctype="multipart/form-data" id="MyForm">
Filter
<div>
Filter Options:
</div>
<div>
#Html.DropDownList("test", new SelectList(Model.MyFilterList,Model.SelectedFilter))
</div>
<h3>Insert Instructions Here</h3>
#{
var DB = Database.Open("CHAVI");
var grid = new WebGrid(DB.Query("SELECT * FROM [TicketQueue]"), null, null, 20);
#grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column(header: "Link", style: "labelcolumn", format: (item) => Html.ActionLink("Edit Item", "EditQueue", new { id = item.QueueID})),
grid.Column("Description", "Description"),
grid.Column("QueueDate", "QueueDate"),
grid.Column("Note", "Note"),
grid.Column("Status", "Status"),
grid.Column("LastUpdated", "LastUpdated")
)
)
}
</form>
The grid part is working fine (and the query). The problem is in the dropdown, it isn't set to anything there. Any thoughts? Thanks.
Are you not passing the model to view?
Should it not be
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View(model);
}
Try using:-
public ActionResult Queue()
{
QueueFilterModel model = new QueueFilterModel()
{
SelectedFilter = "All",
query = "SELECT * FROM [CHAVI].[dbo].[TicketQueue]",
MyFilterList = new List<string>()
};
model.MyFilterList.Add("All");
model.MyFilterList.Add("Open");
model.MyFilterList.Add("Closed");
return View(model);
}

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.

Resources