I have mvc.grid/webgrid with dropdownlist. On dropdown select change event I am getting only first row of dropdown selected value. When Selecting second row dropdown then getting value of first dropdown only which is incorrect.
Can anyone help me on this.
function fillAmount(){
var ddlmonthId = $("#ddlmonth").val();
#using (Html.BeginForm("Save", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#webGrid.GetHtml(
htmlAttributes: new { #id = "WebGrid", #class = "Grid" },
columns: webGrid.Columns(
webGrid.Column("key_cit", "key_cit"),
webGrid.Column("key_date", "key_date"),
webGrid.Column("key_veh_license", "key_veh_license"),
webGrid.Column(format: #<text>
#Html.DropDownList("ddlmonth", (IEnumerable<SelectListItem>)#ViewBag.ddlmonth, new { onchange = "fillAmount(this)", #class = ".we" });
</text>),
webGrid.Column("AmountPayPlan", "Country"),
// webGrid.Column("Country", "Country"),
webGrid.Column(null, null, format: #<text>#Html.ActionLink("Select", null, null, new { #class = "select" })</text>)
))
}
Related
Is it possible to use razor syntax to add kendo widgets inside of the Content of a Kendo Window?
Here is an example of what I am trying to do but the kendo widgets aren't loading properly:
<div id="window1"></div>
#(Html.Kendo().Window()
.Name("productWindow")
.Title("Additional Settings")
.Width(400)
.Modal(true)
.AppendTo("#window1")
.Visible(false)
.Actions(actions => actions.Minimize().Maximize().Close())
.Content(#<text>
<label asp-for="ProductId"></label>
#(Html.Kendo().DropDownList()
.Name("ProductId")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Prod 1",
Value = "1"
},
new SelectListItem() {
Text = "Prod 2",
Value = "2"
},
new SelectListItem() {
Text = "Prod 3",
Value = "3"
},
new SelectListItem() {
Text = "Prod 4",
Value = "4"
}
})
.Value("2")
.HtmlAttributes(new { style = "width: 100%" })
.Deferred()
)
<span asp-validation-for="ProductId" class="text-danger"></span>
</text>)
.Deferred()
)
You can have the window make another call to ask for it's content. That call will return the partial with the view for the window.
In Parent View
#model ProductFormViewModel
#(Html.Kendo().Window().LoadContentFrom("Action", "Controller",new object{"detailID",model.DetailID);
Controller
public ActionResult Action(int detailID)
{
var detailModel=LoadDetail(DetailID);
return PartialView("MyWindowPartual",detailModel);
}
Window Detail PartialView
#model AdvancedProductSettingsViewModel
#(Html.Kendo().DropDownList()...
And have the controller return a View() or PartialView().
I have declared the webgrid inside a div in a partial view and my delete button is in Main View.Now I want a functionality in which when i click the delete button my webgrid should get refreshed only not whole page(Main View).
**I want to refresh only partial View which Contains webgrid using jquery in mvc
My partial View Code is as follows:
WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station");
//WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station", ajaxUpdateContainerId: "grid1");
string Message = "";
if (#ViewBag.NoData != null)
{
Message = ViewBag.NoData.ToString();
}
<div id="UserMainDiv">
#if (Model.Count() > 0)
{
<div id="grid1" class="row container" style="width:84%;margin-left:8%;">
<div class="col-md-12" style="width:100%;color:black;margin-top:10px;padding-left:0px;padding-right:0px;">
#grid.GetHtml(
htmlAttributes: new { id = "grid" },
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
//mode: WebGridPagerModes.All,
//firstText: "",
//lastText: ">>",
//previousText: "<",
//nextText: ">",
columns: grid.Columns
(
//Here I am going to add checkbox column
//Here I am going to add checkbox column
grid.Column(format: #<text> <input type="checkbox" value="#item.ID" name="ids" /> </text>, header: "{checkall}"),
//grid.Column("ID"),
#*grid.Column("Name",format: #<text>#Html.ActionLink((string)item.Name, "AddEdit", "gridchk", new { id = item.id })</text>),*#
grid.Column("Station", format: #<text>#Html.ActionLink((string)item.Station, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
grid.Column("FlightNo", "Flight No", format: #<text>#Html.ActionLink((string)item.FlightNo, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
grid.Column("FlightDate", "Flight Date", format: #<text>#Html.ActionLink((string)item.FlightDate.ToString("MM/dd/yy"), "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("FlightDate", "Flight Date", format: (item) => item.FlightDate != null ? item.FlightDate.ToString("MM/dd/yy") : "NULL"),
grid.Column("PaxNo", "Pax No", format: #<text>#Html.ActionLink((string)item.PaxNo != null ? (string)item.PaxNo : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("PaxNo", "Pax No", format: (item) => item.PaxNo != null ? item.PaxNo : "NULL"),
grid.Column("PaxNoOwnward", "PaxNo Onward", format: #<text>#Html.ActionLink((string)item.PaxNoOwnward != null ? (string)item.PaxNoOwnward : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>),
//grid.Column("PaxNoOwnward", "PaxNo Onward", format: (item) => item.PaxNoOwnward != null ? item.PaxNoOwnward : "NULL"),
grid.Column("TextMsg", format: #<text>#Html.ActionLink((string)item.TextMsg, "EditEmployee", "Manage", new { id = item.ID }, new { #class = "modal1" })</text>)
)
)
</div>
</div>
}
#*</div>*#
else
{
<div style="width:80%;margin-left:10%;">
<div class="row container">
<div class="col-md-12" style="width:100%;color:black;margin-top:10px;text-align:center;">
#Html.Label("", Message, new { id = "lblMessage" })
</div>
</div>
</div>
}
</div>
And My Main page view where i have delete button button code declared.
With that I am using Jquery
$('#btnDelete').click(function (e) {
var command = $('#btnDelete').val();
var myArray = [];
$("#gridtable tbody tr td:nth-child(1)").find('input[type="checkbox"]:checked').each(function () {
myArray.push(($(this).val()));
});
e.preventDefault();
var url = '#Url.Action("DeleteUser", "CreateUser")';
$.ajax({
url: url,
type: 'GET',
data: { ids: myArray },
dataType: 'html',
success: function (data) {
// $("#demoaArea").html(data);
location.reload();
// window.location.href = url;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error; ' + eval(error));
alert("Status: " + textStatus); alert("Error: " + errorThrown);
//alert('Error!');
}
});
});
My Delete controller code:
public Actionresult DeleteStudent(int ids)
{
// delete the record from ID and return true else false
}
In your ajax call success, instead of reload , use the below one.
$('#UserMainDiv').html(data)
and in your controller return partialview instead of whole view.
public Actionresult DeleteStudent(int ids)
{
// delete the record from ID and return true else false
return PartialView("PartialViewName",model);
}
I am new to MVC and would like to know, how to submit whole grid data on submit button click to controller at once using viewmodel.
In View
#model prjMVC4Training.Models.BookViewModel
#{
ViewBag.Title = "Index";
var categories = ViewBag.BookCategories;
var authors = ViewBag.BookAuthors;
var grid = new WebGrid(source: Model.BookData, canSort: true, canPage:true);
}
#using (Html.BeginForm("BookPost", "Book", FormMethod.Post, new { #id = "grid" }))
{
<h2>Book Index Page</h2>
#Html.HiddenFor(m => m.PrimaryKeyID)
#grid.GetHtml(
tableStyle: "table",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
headerStyle: "header",
columns: grid.Columns(
grid.Column("Actions",
style: "col1",
canSort: false,
format: #<text>
<button type="button" class="edit-book display-mode" id="#item.BookID">Edit</button>
<button type="button" class="save-book edit-mode" id="#item.BookID">Save</button>
<button type="button" class="cancel-book edit-mode" id="#item.BookID">Cancel</button>
</text>),
grid.Column("BookTitle",
style: "col2",
canSort: true,
format: #<text>
<span id="dBookTitle" class="display-mode">#item.BookTitle</span>
#Html.TextBox("BookData_" + (int)item.BookID + "__BookID", (string)item.BookTitle, new { #class = "edit-mode", size = 45 })
</text>),
grid.Column("AuthorName",
header: "Author",
style: "col3",
canSort: true,
format: #<text>
<span id="dAuthorName" class="display-mode">#item.AuthorName</span>
#Html.DropDownList("AuthorID_" + (int)item.BookID, (ViewBag.BookAuthors as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.AuthorID
}), new { #class = "edit-mode" })
</text>),
grid.Column("CategoryName",
style: "col4",
canSort: true,
format: #<text>
<span id="dCategoryName" class="display-mode">#item.CategoryName</span>
#Html.DropDownList("CategoryID_" + (int)item.BookID, (ViewBag.BookCategories as SelectList).Select(option => new SelectListItem
{
Text = option.Text,
Value = option.Value,
Selected = option.Value == #item.CategoryID
}), new { #class = "edit-mode" })
</text>),
grid.Column("BookISBN",
style: "col5",
format: #<text>
<span id="dBookISBN" class="display-mode">#item.BookISBN</span>
#Html.TextBox("BookISBN_" + (int)item.BookID, (string)item.BookISBN, new { #class = "edit-mode", size = 20 })
</text>),
grid.Column("IsMember",
style: "",
format: #<text>
<span id="dMember" class="display-mode">#item.IsMember</span>
<input type="checkbox" id="MemberID_" + (int)item.BookID name="MemberID" #(item.IsMember == true ? "Checked" : null) class="edit-mode"/>
</text>)))
<button type="submit" value="Save Book Data">Save Book Data</button>
}
On submit button, I want to pass the value to controller
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BookPost(BookViewModel obj)
{
ViewBag.BookCategories = new SelectList(BookHelperData.GetBookCategories(), "CategoryID", "CategoryName", "20");
ViewBag.BookAuthors = new SelectList(BookHelperData.GetAuthors(), "AuthorID", "AuthorName");
//ViewBag.BookAuthors = BookHelperData.GetAuthorsList();
var Book = BookHelperData.GetBooks();
return View(Book);
}
My ViewModel Class is like this-
public class BookViewModel
{
public int PrimaryKeyID { get; set; }
public List<Book> BookData { get; set; }
}
You can write a generic method which loops all the data in grid and transform it to json structure.
function gridTojson() {
var json = '{';
var otArr = [];
var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
if ($(this)[0].rowIndex != 0) {
x = $(this).children();
var itArr = [];
x.each(function () {
if ($(this).children('input').length > 0) {
itArr.push('"' + $(this).children('input').val() + '"');
}
else {
itArr.push('"' + $(this).text() + '"');
}
});
otArr.push('"' + i + '": [' + itArr.join(',') + ']');
}
})
json += otArr.join(",") + '}'
return json;
}
Now on submit button click you need to pass the data to controller.
$('#btnsave').click(function (e) {
//debugger;
var _griddata = gridTojson();
var url = '#Url.Action("UpdateGridData")';
$.ajax({
url: url,
type: 'POST',
data: { gridData: _griddata }
}).done(function (data) {
if (data != "") {
$('#message').html(data);
}
});
});
Now on controller serialize the data back
public ActionResult UpdateGridData(string gridData)
{
var log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
return Json("Update Successfully");
}
Here is the post regarding this.
I have a webgrid with dropdownlist and onchange it postback the page. I am trying to get the selected value of the dropdownlist.
Following is my Controller.
public ViewResult Index()
{
//var albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre);
var model = new AlbumActionModel { Actions = new[] { new SelectListItem { Text = "Accept", Value = "Accept" }, new SelectListItem { Text = "Deny", Value = "Deny" } }, Albums = db.Albums.Include(a => a.Artist).Include(a => a.Genre) };
return View(model);
}
Following is my View.
<div>
#{
WebGrid grid = new WebGrid(Model.Albums, defaultSort: "Title", selectionFieldName: "SelectedRow");
}
#using (Html.BeginForm("Index", "Album", FormMethod.Post, new { id = "TheForm" }))
{
#grid.GetHtml(columns: grid.Columns(grid.Column("Edit",
format: #<text> #Html.ActionLink("Edit", "Edit", new { id = item.AlbumId })></text>),
grid.Column("AlbumId"),
grid.Column("Title"),
grid.Column("Action",
format:
#<span>
#{var index = item.AlbumId.ToString();}
#Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--", new { onchange = "this.form.submit();" })
</span>),
grid.Column("Delete",
format: #<text> #Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })></text>)))
</div>
Thanks in advance.
In your dropdownlist try the following statement:
#Html.DropDownList("Actions" +((string)index), Model.Actions, "--Select One--",new { #onchange = "Submit(this.value);" })
Now write a function in your <script> tag to post it to the page
<script type="text/javascript">
function Submit(e)
{
//write it to post to the controller using ajax
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("Submit", "ControllerName")',
data: ({ value: e}),
success: function (result) {
//do something
}
,
error: function (result) {
//do something
}
});
}
</script>
Hope this helps.
i want to hide/show a button on condition but not able to do it inside view.
#{
ViewBag.Title = "Mapping";
WebGrid grid = null;
if (ViewBag.Mappings != null)
{
grid = new WebGrid(source: ViewBag.Mappings,
defaultSort: "Id",
canPage: true,
canSort: true,
rowsPerPage: 10);
}
}
<h3>#ViewData["Message"]</h3>
#if (grid != null)
{
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("", header: null, format: #<text>#Html.ActionLink("Edit", "Index", new { uid = (Guid)item.id, userAction = "Edit" }, new { #class = "edit" })
#Html.ActionLink("Delete", "Index", new { uid = (Guid)item.id, userAction = "Delete" }, new { #class = "Delete" })</text>),
grid.Column("PricingSecurityID"),
grid.Column("CUSIP"),
grid.Column("Calculation")
)
)
}
if(#ViewBag.Mappings != null)
{
#Html.ActionLink("Update", "Index", new { userAction = "Update" }, new { #class = "Update" })
}
In the above view if ViewBag.Mappings != null then i'm populating webgrid.
And if webgrid is populated I need to show a Update button under a webgrid, but where i go wrong to achieve this in condition ?
Move the "#" on the 4th line from the bottom:
Before:
if(#ViewBag.Mappings != null)
After:
#if(ViewBag.Mappings != null)