DropDown change show partial - asp.net-mvc

I have used from dropdownlist in page.
I want, when change selected id info, load bottom of page.
first time that page load is true,but with dropdown change load info in new page, not part of current page.
Fill dropdown list
public ActionResult selVahedList(int IdType, int IdChoose)
{
ViewBag.ChooseItem = IdChoose;
IEnumerable<Lcity> Lcitys = Dbcon.Lcitys;
var model = new CityViewMode
{
Lcitys = Lcitys.Select(x => new SelectListItem
{
Value = x.Citycode.ToString(),
Text = x.CityName
})
};
return View(model);
});
Partial view shows after dropdown changed
public ActionResult selVahedListAjax(CityViewMode model)
{
int idcity=Convert.ToInt32(model.SelectedCitycode);
// int idcity = 1;
ViewBag.Reshteh = 1;
//string IdCity = base.Request["SelValue"].ToString();
var res = Dbcon.TaavoniInfos.Where(m => m.IDReshteh == 1 && m.Citycode ==idcity);
return PartialView("selVahedListAjax", res);
}
view page
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "LoadData",
LoadingElementId="loadAdmin"
};
#using (Ajax.BeginForm("selVahedListAjax",ajaxOpts))
{
<fieldset>
<div class="PContent">
<p class="DroplistCity" id="DroplistCity">
#Html.DropDownListFor(
x => x.SelectedCitycode,
new SelectList(Model.Lcitys, "Value", "Text",""))
<div id="LoadData">
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem })
</div>
</div>
</fieldset>
}
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#SelectedCitycode').change(function () {
this.form.submit();
});
});
</script>
thanks for your help
my partial view code is: #model
IEnumerable<TaavonS.Models.TaavoniInfo>
<ul>
#foreach (var item in Model)
{
<li>:<b>#Html.DisplayFor(modelItem => item.SName)</b></li>
<li>:<b>#Html.DisplayFor(modelItem => item.ModirName)</b></li>
<li><img src="#Url.Content("~/Content/img/list16.png")" alt=""/>
#Html.ActionLink("detail....", "Detaild",new { codef= item.Scode }, new { #class = "openDialog", data_dialog_id = "emailDialog", data_dialog_title = "" } )
<hr class="separatorLine"/></li> when i load page is true but after dropdownlist is nt work
<li>
#if (!string.IsNullOrEmpty(item.TablighatPic))
{
<img src="#Url.Content("~/Content/img/eye.png")"/> #Html.ActionLink("تبلیغات....", "showImg", new { code = item.Scode }, new { #class = "openImg", data_dialog_id = "mailDialog" })<hr class="separatorLine"/>
}
</li>
}
</ul>

I think you need to change your ajaxOptions:
AjaxOptions ajaxOpts = new AjaxOptions
{
UpdateTargetId = "LoadData",
LoadingElementId="loadAdmin",
InsertionMode = InsertionMode.Replace // add this line
};
Add the parameter to the beginForm call
#using (Ajax.BeginForm("selVahedListAjax",
new { IdReshte = ViewBag.ChooseItem }, //add this to the Ajax.BeginForm call
ajaxOpts ))
{
and remove this line from the target div if you don't want the ajax call performed before the user chooses anything
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem })

Related

How to display two views using two different models on the same web page in ASP.NET MVC

Here is the code for controllers and view. I want to display the both views on the same webpage in ASP.NET MVC. How to achieve this goal?
Controller:
public ActionResult LetterList()
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return View(obj);
}
public ActionResult Showimage(string ListId)
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return View(letterList);
}
View Of LetterList
#model LetterPage.Models.ModelView
<div>
#{
foreach (var item in Model.letterDetail)
{
<div>
#item.ListName
</div>
}
}
</div>
ShowImage view:
#model IList< LetterPage.Models.hurf_e_tahaji>
#{
ViewBag.Title = "ShowImage";
}
<table class="table">
<tr>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<img src="#Url.Content("item.Letter_Pic") "/>
</td>
</tr>
}
</table>
When I created these views as partial views and render them into another view exception occurs on the Foreach loop at model.
You can use PartialView:
[HttpPost]
public PartialViewResult LetterList()
{
if (Request.IsAjaxRequest())
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return PartialView(obj);
}
return null;
}
[HttpPost]
public PartialViewResult Showimage(string ListId)
{
if (Request.IsAjaxRequest())
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return PartialView(letterList);
}
return null;
}
Then you have to define your partial views (like code you posted), And inside the main view:
<div class="LetterList">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
<div class="Showimage">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$.post('/Home/LetterList', function(data) {
$('.LetterList').html(data);
});
$.post('/Home/Showimage/' + ListId, function(data) {
$('.Showimage').html(data);
});
});
</script>
}

MVC gridview return popup with html when select filter or click next page

mvc gridview return popup with html when select filter or click next page how can I fix this problem in this code show my partial gridview my view and controller action
PartialView
#{
Html.DevExpress().GridView(settings =>
{
settings.Name = "TestList";
settings.CallbackRouteValues = new { Controller = "Admin", Action = "TestList" };
settings.CommandColumn.Visible = true;
settings.KeyFieldName = "ID";
settings.CommandColumn.Visible = false;
settings.Columns.Add(column =>
{
column.Caption = "Edit";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Edit", "TestListEdit", "admin",
new { id = content.KeyValue }, null)));
});
settings.Columns.Add(column =>
{
column.Caption = "Delete";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Delete", "TestListDelete", "admin",
new { id = content.KeyValue }, null)));
});
settings.Columns.Add(column =>
{
column.Caption = "Manage";
column.Visible = true;
column.SetDataItemTemplateContent(content =>
ViewContext.Writer.Write(
Html.ActionLink("Manage Questions", "ManageQuestions", "admin",
new { id = content.KeyValue }, null)));
});
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.Columns.Add("ID");
settings.Columns.Add("Title");
settings.Columns.Add("Description");
settings.Columns.Add("Lang_ID");
settings.Columns.Add("TryDescription");
}).Bind(Model).Render();
}
this is my View
#model List<FastCreditTraining.Models.AdminTestListEditingModel>
#{
ViewBag.Title = "TestList";
Layout = "~/Views/Shared/_adminLayout.cshtml";
}
#{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "English",
Value = "1"
});
listItems.Add(new SelectListItem
{
Text = "Հայերեն",
Value = "2",
});
}
<body>
<div style="display:inline-block;float:right; margin-right:30px; margin-top:10px">
#Html.ActionLink("Create", "TestListCreate", "admin", new { #class = "LangButton" })
</div>
<div style="display:inline-block">
<form style="display:inline-block" name="tActive" id="tActive" method="get">
<div style="margin-left:50px; display:inline-block;">
<p style="display:inline-block">#Resources.Resource.DisplayActiveTests</p>
#Html.CheckBox("tActive", true)
</div>
<div style="margin-left:100px; display:inline-block;">
<p style="display:inline-block">#Resources.Resource.SetLanguageInterfaceEdit</p>
#Html.DropDownList("langSwitch", listItems)
</div>
<input type="submit" name=" asdasd" value="Filter">
</form>
</div></body>
#{Html.RenderPartial("_GridViewTestListPartial",Model);}
And this is my controller action
![\[Authorize\]
public ActionResult TestList(string tActive, string langSwitch)
{
//tActive and langSwitch choose getting tests with procedure getTests_Result
List model1;
if (tActive == null || langSwitch == null)
{
model1 = db.getTests(true, 1).ToList();
}
else
{
model1 = db.getTests(Convert.ToBoolean(tActive), Convert.ToInt32(langSwitch)).ToList();
}
///////////////////end of getting///////////////////
// Fill new created model from database test lists and departaments and positions
List _Departments = db.T_Department_Lang.ToList();
List _Positions = db.T_Position_Lang.ToList();
List _checkForDep = new List();
List _checkForPos = new List();
foreach (var item in _Departments)
{
_checkForDep.Add(new bool());
}
foreach (var item in _Positions)
{
_checkForPos.Add(new bool());
}
for (int i = 0; i < model1.Count; i++)
{
allModels.Add(new AdminTestListEditingModel()
{
ID = model1\[i\].ID,
Date_Added = model1\[i\].Date_Added,
Limit = model1\[i\].Limit,
IS_Active = model1\[i\].IS_Active,
Allow_Back = model1\[i\].Allow_Back,
Title = model1\[i\].Title,
Description = model1\[i\].Description,
Lang_ID = model1\[i\].Lang_ID,
S_Changed = model1\[i\].S_Changed,
Question_qnt = model1\[i\].Question_qnt,
Pos_Save = model1\[i\].Pos_Save,
Question_test_qnt = model1\[i\].Question_test_qnt,
TryDescription = model1\[i\].TryDescription,
qCount = model1\[i\].qCount,
TestList_Id = model1\[i\].ID,
Departments = _Departments,
Positions = _Positions,
checkForDep = _checkForDep,
checkForPos = _checkForPos
});
}
//////////////// end fill //////////////////
Session\["allModels"\] = allModels;
return View(allModels);
}][1]
Return PartialView instead of View to resolve this issue:
//return View(allModels);
return PartialView(allModels);
See the Why can the alert message with the HTML/JavaScript/CSS content appear when using callback-aware extensions? knowledge resource to learn more.

MVC 5 view not autoupdating partial view

I have a controller
public class AccountDetailsController : Controller
{
private readonly IAccountStatsRepository _accountStatsRepository;
public AccountDetailsController(IAccountStatsRepository accountStatsRepository)
{
_accountStatsRepository = accountStatsRepository;
}
public ActionResult Details(string accountEmail)
{
var stats = _accountStatsRepository.Get(accountEmail);
var accountDetailsViewModel = new AccountDetailsViewModel
{
Email = accountEmail,
Money = stats.TotalCredits
};
return View(accountDetailsViewModel);
}
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] // every 3 sec
public ActionResult GetLatestLogging(string email)
{
//if (email == null || email != null)
//{
var list = new List<LogViewModel>();
return PartialView("LatestLoggingView", list);
//}
}
}
And a View
#using FutWebFrontend.ViewModels
#model AccountDetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>#Model.Email</h2>
<div>
<h4>Account details</h4>
Money #String.Format("{0:0,0}", Model.Money)
</div>
<div id="loggingstream">
#Html.Partial("LatestLoggingView", new List<LogViewModel>())
</div>
<hr />
<dl class="dl-horizontal"></dl>
<p>
#Html.ActionLink("Back to List", "index", "AccountControl")
</p>
<script type="text/javascript">
$(function() {
setInterval(function () { $('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});
</script>
But when I go to my page and put a breakpoint in GetLatestLogging then nothing happens
If I hit F12 in chrome I get "Uncaught ReferenceError: $ is not defined "Details:67
From what I can gather, this should hit my Get method every 3 seconds, but I must have made a simple error somewhere
Try this
$( document ).ready(function() {
setInterval(function () {$('#loggingstream').load('/AccountDetails/GetLatestLogging/#Model.Email'); }, 3000);
});

MVC jQuery POST fails to update the cart information in the second request

I am just trying to update the cart using jQuery POST. It's success with the first request. However, it's seem to throw a 500 server error within the second request. The problem is after I debug it. The Action Result at the second time it's try to render the view instead of sending the JSON object to the callback function. Here is my code bellow.
Here is my Action Result inside my cart
[HttpPost]
public ActionResult UpdateResultCart(int productId)
{
// Retrieve the album from the database
var addedProduct = _db.Products
.Single(pr => pr.ProductID == productId);
// Add it to the shopping cart
var cart = ShoppingCartModel.GetCart(this.HttpContext);
cart.AddToCart(addedProduct);
// Set up our ViewModel
var shoppingCartData = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
return Json(shoppingCartData);
}
Here is my JavaScript function
$(function () {
$("#AddCartProduct").click(function () {
var productId = $(this).attr("data-id");
if (productId != '') {
// Perform the ajax post
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("/Cart/UpdateResultCart", { "productId": productId }, function(data) {
alert("success");
$('#cart-item').text(": " + data.CartItems.length + " Items");
$('#total-price').text("Total Price:" + numberToCurrency(data.CartTotal));
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); });
}
});
});
Finally,Here is my HTML Element in the partial view that needs to be updated
#if (Request.IsAuthenticated) {
<ul>
<li>
#using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
{
#Html.AntiForgeryToken()
Log off
}
</li>
|
<li>Account</li>
|
<li>
Cart
<label class="cart-item">: 0 Items</label>|
<label class="total-price">$0.00</label>
</li>
</ul>
} else {
<ul>
#*<li>#Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>*#
<li>#Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>|
<li>Account</li>|
<li>
Cart
<label class="cart-item">: 0 Items</label>|
<label class="total-price">$0.00</label>
</li>
</ul>
}
Thanks

Can't pass selected value DropDownListFor to javascript function

My simpel test Model:
public class MovieModel {
public string SelectedCategorieID { get; set; }
public List<CategorieModel> Categories { get; set; }
public MovieModel() {
this.SelectedCategorieID = "0";
this.Categories = new List<CategorieModel>() {new CategorieModel {ID = 1,
Name = "Drama"},
new CategorieModel {ID = 2,
Name = "Scifi"}};
}
}
public class CategorieModel {
public int ID { get; set; }
public string Name { get; set; }
}
My Home controller action Index:
public ActionResult Index() {
Models.MovieModel mm = new Models.MovieModel();
return View(mm);
}
My strongly typed View:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
<script type="text/javascript">
function categoryChosen(selectedCatID) {
// debugger;
var url = "Home/CategoryChosen?SelectedCategorieID=" + selectedCatID;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get)) {
<fieldset>
Movie Type
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID", "Name", Model.SelectedCategorieID), "---Select categorie---")
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" onclick="categoryChosen('#Model.SelectedCategorieID');" />
<div id="minicart">
#Html.Partial("Information")
</div>
Please ignore the first input, because I'm using the second input with 'Minicart test' on it (the HTML.Beginform is there to learn something else later). The mini cart stuff is from another tutorial, I apologize. Don't let it distract you please.
When the button is clicked categoryChosen jQuery is called, which calls the action:
[AcceptVerbs("POST")]
public ActionResult CategoryChosen(string SelectedCategorieID) {
ViewBag.messageString = SelectedCategorieID;
return PartialView("Information");
}
The partial view Information looks like this:
#{
ViewBag.Title = "Information";
}
<h2>Information</h2>
<h2>You selected: #ViewBag.messageString</h2>
My question is why is Model.SelectCategorieID zero (Model.SelectCategorieID = 0) even after I changed the value in the dropdownlist? What am I doing wrong? Thank you very much in advance for answering. If you need any information or anything in unclear, please let me know.
My question is why is Model.SelectCategorieID zero
(Model.SelectCategorieID = 0) even after I changed the value in the
dropdownlist?
That's because you have hardcoded that value in your onclick handler:
onclick="categoryChosen('#Model.SelectedCategorieID');"
If you want to do that properly you should read the value from the dropdown list:
onclick="categoryChosen(this);"
and then modify your categoryChosen function:
<script type="text/javascript">
function categoryChosen(ddl) {
// debugger;
var url = 'Home/CategoryChosen';
$.post(url, { selectedCategorieID: $(ddl).val() }, function (data) {
$('#minicart').html(data);
});
}
</script>
Also I would recommend you using an URL helper to generate the url to invoke instead of hardcoding it in your javascript function. And last but not least, I would recommend you doing this unobtrusively, so that you could put this in a separate javascript file and stop mixing markup and script.
So here's how your code will look like after taking into consideration my remarks:
#model MvcDropDownList.Models.MovieModel
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get))
{
<fieldset>
Movie Type
#Html.DropDownListFor(
m => m.SelectedCategorieID,
new SelectList(Model.Categories, "ID", "Name"),
"---Select categorie---",
new {
id = "categoryDdl"
data_url = Url.Action("CategoryChoosen", "Home")
}
)
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
}
<input type="button" value="Minicart test" id="minicart-button" />
<div id="minicart">
#Html.Partial("Information")
</div>
and then in your separate javascript file unobtrusively subscribe to the click handler of your button and send the AJAX request:
$(function() {
$('#minicart-button').click(function() {
// debugger;
var $categoryDdl = $('#categoryDdl');
var selectedCategorieID = $categoryDdl.val();
var url = $categoryDdl.data('url');
$.post(url, { selectedCategorieID: selectedCategorieID }, function (data) {
$('#minicart').html(data);
});
});
});
Provide an id for your dropdownlist:
#Html.DropDownListFor(m => m.SelectedCategorieID, new SelectList(Model.Categories, "ID",
"Name", Model.SelectedCategorieID), new {id = "myDropDownList"})
And your javascript function as follows:
<script type="text/javascript">
function categoryChosen() {
var cat = $("#myDropDownList").val();
var url = "Home/CategoryChosen?SelectedCategorieID=" + cat;
$.post(url, function (data) {
$("#minicart").html(data);
});
}
</script>
Why your code did not work?
onclick="categoryChosen('#Model.SelectedCategorieID')
is generated as
onclick="categoryChosen('0')
because the value of SelectedCategorieID is 0 when it is generated.

Resources