MVC 3 Webgrid with dropdownlist, get selected value on postback - asp.net-mvc

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.

Related

How to delete multiple records in a webgrid by clicking a delete button which is declared in a partial view in MVC

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

How to bind a WebGrid in a PartialView, which is in JQueryUI ModalPopup

I have this PartialView, which is loaded from the Layout of an MVC4 application.
On a button click in the main navigation menu the method SearchCustomers is called in an ajax post (shown below). Everything seems to work. Fiddler shows Data is coming back as supposed however the grid is not visible in the Popup. I wonder what am I doing wrong?
The Partial View
#model Invoice.Web.ViewModels.SearchCustomerWindowVM
<h2>Search Results</h2>
<div id="resultsGrid">
#{
if (Model.CustomersList != null)
{
var grid = new WebGrid(Model.CustomersList, rowsPerPage: 6, ajaxUpdateContainerId:"searchResults ");
#grid.GetHtml(
fillEmptyRows: true,
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new [] {
grid.Column("Forename", canSort: false),
grid.Column("Surname"),
grid.Column("PostCode"),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "Edit", new { id=item.CustomerID} )
|
#Html.ActionLink("Delete", "Delete", new { id=item.CustomerID} )
</text>
)
}
)
}
}
The Ajax Post - I guess the problem is here!!
<script>
$( "#searchCustomers" ).dialog({
autoOpen: false,
height: 350,
width: 700,
modal: true
});
$("#searchButton")
.button()
.click(function() {
$("#searchCustomers").dialog("open");
});
function searchCustomers() {
var forename = $("#Forename").val();
var surname = $("#Surname").val();
var postCode = $("#PostCode").val();
debugger;
var request = {
foreName: forename,
surName: surname,
postCode: postCode
};
$.ajax({
type: "POST",
url: "/Customer/SearchCustomers",
data: JSON.stringify(request),
datatype: "JSONP",
contentType: "application/json; charset=utf-8",
success: function (returndata) {
// if (returndata.ok) {
//$.post(data.Url, function(partial) {
// $('#IdOfDivToUpdate').html(partial);
$("#searchCustomers").dialog("open");
//alert("The File Has Been Downloaded.");
$('#resultsGrid').html(returndata);
//} else {
// window.alert('Error Saving Authorisation.');
//}
}
}
);
}
</script>
The Controller method:
public ActionResult SearchCustomers(string postCode, string surName, string foreName)
{
var model = new SearchCustomerWindowVM();
var modelList = new List<SearchCustomerWindowVM>();
var customersList = _customerRepository.GetAllCustomers().ToList();
foreach (var cust in customersList)
{
model.Forename = cust.FirstName;
model.Surname = cust.Surname;
model.PostCode = cust.ContactDetails.PostCode;
modelList.Add(model);
}
return Json(modelList);
// return Json(new {error = true, message = "all good."});
}
As you see I have tried other approaches in the Ajax post, which I have commented out.
Thanks in advance.
on your controller change the return to partial view
return PartialView("_PartialName", model);
then in the success of your ajax call
$('#searchCustomers').html(result);
$("#searchCustomers").dialog("open");
this way you load the div with the partial view and then open the dialog

Pass webgrid data back to controller via post asp.net mvc

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.

passing model from view to controller using ajax call?

I am making an application, in which it is required to create a lead when user enters the mobile number and tab out, the lead is created if entered mobile number is valid(with all other details on the form). But when i am passing model from view to controller the data i 'm getting null.
View
#{
ViewBag.Title = "EmailQuote";
Layout = "~/Views/Shared/Template.cshtml";
}
#model Max.VirtualSalesManager.UI.ViewModels.LeadViewModel
#{
var data = Html.Raw(Json.Encode(Model));
}
<script src="#Url.Content("~/Scripts/Common.js")" type="text/javascript"></script>
<h2>
EmailQuote</h2>
#using Acidaes.VirtualSalesManager.UI.Helpers
#using (Html.BeginForm("GenerateEQuote", "Quote", FormMethod.Post, new{id="frmEmailQuote" }))
{
#Html.MandatoryLabel("Name", false, new { style = "width: 50px; display: inline" }) #Html.FullName()
#Html.MandatoryLabel("City", false, new { style = "width: 50px; display: inline" }) #Html.DropDownListFor(m => m.CommunicationAddress.City, new SelectList(ViewBag.CityList, "Key", "Value"), "select", new { id = "ddlCity" })
#Html.MandatoryLabel("Mobile No.", false, new { style = "width: 100px; display: inline" }) #Html.TextBoxFor(m => m.MobileNumber, new { style = "width: 100px", id = "txtmobilenumber", onBlur = "createLead('"+#data+"')" })
#Html.MandatoryLabel("Email ID", false, new { style = "width: 80px; display: inline" }) #Html.TextBoxFor(m => m.EmailId, new { style = "width: 100px" })
#Html.HiddenFor(m => m.LeadId)
<input type="submit" id="btnSubmit" />
}
Js
function createLead(data) {
var number = /^[0-9]+$/;
var mobileNumber = document.getElementById('txtmobilenumber').value;
if (mobileNumber.match(number) && mobileNumber.length == 10) {
var jsondata = JSON.stringify(data);
var Parameters = "{'data':'" + ("#frmEmailQuote").serialize() + "'}";
Events.DoServerRequest('/MAXVSM/Quote/test', Parameters, GetLeadId);
}
}
DoServerRequest Function
DoServerRequest: function (url, data, funSuccess) {
$.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: funSuccess,
error: function () {
alert("Error in getting list");
}
});
Controller
[HttpPost]
[ActionName("test")]
public JsonResult test(LeadViewModel data)
{
LeadViewModel t = new LeadViewModel();
t.MobileNumber = data.MobileNumber;
return Json(t);
}
The data reaching fine from view to ajax function, but when the data is reaching to controller it is null.
Try removing contentType from your ajax call:
DoServerRequest: function (url, data, funSuccess) {
$.post({
type: "POST",
url: url,
data: data,
async: false,
dataType: "json",
success: funSuccess,
error: function () {
alert("Error in getting list");
}
});
}
The server is not expecting JSON content but application/x-www-form-urlencoded which is the default value.
This means you should also use a normal Javascript object or string as data:
if (mobileNumber.match(number) && mobileNumber.length == 10) {
Events.DoServerRequest('/MAXVSM/Quote/test', $("#frmEmailQuote").serialize(), GetLeadId);
}

Dependency between DropDownList

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

Resources