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.
Related
I have an app where users get three suggestions for their order as datetime:
Don´t worry about the year, just an example.
If none of the suggestions fit users can generate three other suggestions in the future, based on the latest calculated date.
This works only once.
My View:
#using (Ajax.BeginForm("GenerateSuggestionDates", "Home", new { Area = "Planning" }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "planeditbody" }, new { autocomplete = "off", id = "suggestiondatesform" }))
{
#Html.HiddenFor(model => model.LatestDate)
#Html.HiddenFor(model => model.AssemblyOrderID)
<i class="fa fa-refresh mt-2 mr-3" style="float: right; color: grey; cursor: pointer;" onclick="$('#suggestiondatesform').submit();"></i>
}
Model.LatestDate is always set to the latest date in controller, but that latest date works only once.
My Controller:
[HttpPost]
public ActionResult GenerateSuggestionDates(PlanEditSingleViewModel model)
{
var viewModel = new PlanEditSingleViewModel();
Dictionary<int, DateTime> suggestions = new Dictionary<int, DateTime>();
try
{
var date = model.LatestDate.AddDays(1);
var counter = 0;
while (counter >= 0 && counter < 3)
{
if (date.DayOfWeek != DayOfWeek.Saturday && date.DayOfWeek != DayOfWeek.Sunday)
{
suggestions.Add(counter, planningService.CheckDesiredDate(date, true, model.AssemblyOrderID, null, true)[0]);
date = date.AddDays(1);
counter++;
}
else
{
date = date.AddDays(1);
}
}
viewModel.Suggestions = suggestions;
viewModel.LatestDate = date.AddDays(-1);
viewModel.AssemblyOrderID = model.AssemblyOrderID;
return PartialView("~/Views/Shared/Modals/PlanEditBodySingle.cshtml", viewModel);
}
catch (Exception e)
{
return PartialView("~/Views/Shared/Modals/PlanEditBodySingle.cshtml", null);
}
}
I can´t find what´s wrong here. Any hints, tipps, suggestions?
Thanks in advance!
Something seemed to be wrong with the binding (?).
I changed the code to this:
#using (Ajax.BeginForm("GenerateSuggestionDates", "Home", new { Area = "Planning", LatestDate = Model.LatestDate.ToString(), AssemblyOrderID = Model.AssemblyOrderID }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "planeditbody" }, new { autocomplete = "off", id = "suggestiondatesform" }))
{
<i class="fa fa-refresh mt-2 mr-3" style="float: right; color: grey; cursor: pointer;" onclick="$('#suggestiondatesform').submit();"></i>
}
Accordingly I edited the controller code. This works.
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 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)
I have 2 select field in ascx file:
<%=Html.DropDownList("CityID", new SelectList(Model.Cities, "Code", "Name"), new Dictionary<string, object>
{
{"class", "styled"}
})
%>
<%=Html.DropDownList("EstablishmentID", new SelectList(Model.Establishments, "OID", "Name"),
"All Establishment", new Dictionary<string, object>
{
{"class", "styled"}
})
%>
I want that a values of EstablishmentId change when user select new value in CityID.
How can I do this?
Thanks.
PS. ViewEngine is WepPages.
cascading Country and state DDL
#Html.DropDownListFor(model => model.CountryId, Model.CountryList, "--Select Country--", new { #class = "CountryList", style = "width:150px" })
#Html.DropDownListFor(model => model.StateId, Model.StateList, "--Select State--", new { #class = "StateList", style = "width:150px" })
<script type="text/javascript">
$(document).ready(function () {
$.post("/Client/GetModels", { id: $(".CountryList").val() }, function (data) {
populateDropdown($(".StateList"), data);
});
$(".CountryList").change(function () {
$.post("/Client/GetModels", { id: $(this).val() }, function (data) {
populateDropdown($(".StateList"), data);
});
});
});
function populateDropdown(select, data) {
$(".StateList").empty();
$.each(data, function (id, option) {
$(".StateList").append("<option value='" + option.StateId + "'>" + option.State + "</option>");
});
}
</script>
Try this
In view
<div class="popup_textbox_div" style="padding: 0pt;">
<%=Html.DropDownList("CityId", new SelectList(Model.Cities, "Code", "Name", 0), "---Select City---", new { #class = "popup_textbox popup_dropdown valid" })%>
</div>
<div class="popup_textbox_div" style="padding: 0pt;">
<select class="popup_textbox popup_dropdown valid" id="OID" name="Name">
<option>---All Establishment---</option>
</select>
</div>
Add the script
<script type="text/javascript">
$(function () {
$("#CityId").change(function () {
var cityId = $("#CityId").val();
if (!isNaN(cityId) && ( cityId > 0) && ( cityId != null)) {
GetEstablishmentsByAjax(cityId);
}
else {
$("#OID").html("<option value=''>---All Establishment---</option>");
}
});
});
GetEstablishmentsByAjax(cid) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/trail/selectestablishment/" + cid.toString(),
data: "",
dataType: "json",
success: function (data) {
if (data.length > 0) {
var options = "<option value=''> --All Establishment---</option>";
for (s in data) {
var type = data[s];
options += "<option value='" + type.Value + "'>" + type.Text + "</option>";
}
$("#OID").html(options);
}
}
});
}
</script>
In TrailController
public ActionResult selectestablishment(int? id)
{
SelectList establishments = null;
var estb = //put ur code and get list of establishments under selected city
establishments = new SelectList(estb, "OID", "Name");
return Json(establishments, JsonRequestBehavior.AllowGet);
}