How to pass value from controller action method to partial view - javascript

Here I tried using TempData to pass data from controller action method to partial view. But it does not work.
My Controller Code
public class PropertyController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetRequestReport()
{
List<ReportsInfo> reportsList = reportsManager.GetRequestReport(UserName, Locality, "usp_GetResults");
int count = reportsList.Select(x => x.UserId).Distinct().Count();
TempData["Count"] = count;
return PartialView("_Partial1", reportsList);
}
public ActionResult Test(string id)
{
switch (id)
{
case "tab1":
return PartialView("_Results");
case "tab2":
return PartialView("_Results2");
}
return new EmptyResult();
}
}
Index.cshtml
<div id="div-for-partial">
</div>
$(function () {
$('.tab').click(function () {
var id = this.id;
$.get('#Url.Action("Test")', { "id": id }, function (data) {
$('#div-for-partial').html(data);
$('.mvc-grid').mvcgrid();
});
});
});
_Results Partial View
#TempData["Count"]
<br />
<div id="reportList">
#Html.AjaxGrid(Url.Action("GetRequestReport", "Property"))
</div>
_Partial1 Partial View
#model Project.Models.ReportsInfo
#(
Html.Grid(Model)
.Build(columns =>
{
columns.Add(model => model.ApproverName).Titled("Approver Name");
})
.Empty("No records found.")
.Sortable()
.Pageable(pager =>
{
pager.RowsPerPage = 15;
})
)
I have even tried view bag but no luck is there any way to achieve it. Basically I want to pass count of results in TempData and use in partial view

public ActionResult GetRequestReport()
{
List<ReportsInfo> reportsList = reportsManager.GetRequestReport(UserName, Locality, "usp_GetResults");
int count = reportsList.Select(x => x.UserId).Distinct().Count();
ViewData["Count"] = count;
return PartialView("_Partial1");
}
In Partial1 partial View, you can get count in a count variable as shown below and use it where ever you want to.
#(
int count=(int)ViewData["Count"];
Html.Grid(Model)
.Build(columns =>
{
columns.Add(model => model.ApproverName).Titled("Approver Name");
})
.Empty("No records found.")
.Sortable()
.Pageable(pager =>
{
pager.RowsPerPage = 15;
})
)

you never called GetRequestReport() before calling Results partial view, how do you expect to get the value of count passed to Results partial view. Please verify what you are asking.

Related

Can not load book follow by category id in dropdownlist using javascript

i'm having trouble while choose each category, it can't show book of each category. My index code here
#using (Html.BeginForm("Index", "BorrowBook", FormMethod.Post, new { name = "demoForm" }))
{
#Html.DropDownList("id_category", (IEnumerable<SelectListItem>)ViewBag.listTest, "-- Select Category --",
new { onchange = "SelectedIndexChanged()" })
<div> Show list of book in the middle </div>
}
And my controller like that
// GET: BorrowBook
public ActionResult Index(string mess)
{
var query = context.categories.Select(c => new { c.id_category, c.name });
var userInfomatiom = (LibraryAsp.Models.User)Session["USER"];
if (userInfomatiom.Role.id_role == 1)
{
ViewBag.listP = publisherDao.getAll();
ViewBag.listC = categoryDao.getAll();
ViewBag.list = bookDao.getAll();
ViewBag.listTest = new SelectList(query.AsEnumerable(), "id_category", "name");
ViewBag.mes = mess;
return View();
}
else
{
return RedirectToAction("Error", "Home");
}
}
[HttpPost]
public ActionResult Index (Category category)
{
ViewBag.listP = publisherDao.getAll();
ViewBag.listC = categoryDao.getAll();
ViewBag.list = context.books.Where(p => p.id_category == category.id_category).ToList();
return View();
}
When debugging, i found that id category, form, or value is loaded like this
But when i choose each category, i get bug like that:
I think my java script is having problem. But i can't figure out this. Any body can help me, many thanks.
Problem solve, my bad to forget pass data. Should be like that
[HttpPost]
public ActionResult Index (Category category)
{
var query = context.categories.Select(c => new { c.id_category, c.name });
ViewBag.listP = publisherDao.getAll();
ViewBag.listC = categoryDao.getAll();
ViewBag.list = context.books.Where(p => p.id_category == category.id_category).ToList();
ViewBag.listTest = new SelectList(query.AsEnumerable(), "id_category", "name");
return View();
}

Typeahead.js for mvc5 models

I've just downloaded and installed
typeahead.bundle.min.js
typeahead.mvc.model.js
typeahead.css
I've followed the example given and I have a helper in my view
#Html.AutocompleteFor(model => model.NewUser.User_Org, model => model.NewUser.User_Org,"GetOrganisations", "User", false, new { htmlAttributes = new { #class = "form-control" } })
and this action method on my controller
[ActionName("GetOrganisations")]
[ValidateAntiForgeryToken]
public ActionResult GetComboData(string search)
{
JsonResult result = new JsonResult();
if (!string.IsNullOrEmpty(search))
{
GetOrganisationRequestNonPrimary request = new GetOrganisationRequestNonPrimary(search);
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
var organisations = this._organisationService.OrganisationAutoComplete(request);
result.Data = organisations.Organisations.AsQueryable();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
return result;
}
The input box is rendered but when I start typing, nothing happens, I would expect my action method to be hit on the controller, but it isn't. I've got all the prerequisites for typeahead and the mvc helper, yet it just wont work. Is there something I'm missing?

Error populate textbox JS - MVC

I have this code.
The objective of this js is through the dropwdown load the textbox UserMR
But it never finds the UserMR.
I call UserMr model inside Star instantiating a new object.
relationships:
Star contains idModel
Model does not contain IDStar
What is going on?
Model
[CustomValidation(typeof(StarValidation), "DateValidate")]
public partial class Star
{
public virtual string UserMR { get { return this.User.UserMR; } set { this.UserMR = value;} }
public Model User = new Model();
View inside "STAR"
#Html.EditorFor(i => i.IdModel, "StarModel", new { onchange = "updateUserMR($(this))" })
#Html.DisplayFor(i => i.UserMR)
<script type="text/javascript">
function updateUserMR(model) {
var user = model.brother("#Html.NameFor(x => x.UserMR)");
var idModel = model.val();
user.empty();
if (idModel != null && idModel != "")
user.loadOptions("#Url.Action("ListJsonUserMR", "Model")?idModel=" + idModel, true, true);
}
</script>
Controller
public JsonResult ListJsonUserMR(int idModel)
{
var model = this.service.GetUserMr(idModel).Select(x => new
{
Value = x.Id,
Description = x.UserMR
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
Service
public IEnumerable<Model> GetUser(int idModel)
{
return base.context.Models
.Where(x => x.Id == idModel);
}
Error

MVC 4 Razor - Creating a dynamic DropDownList

I'm trying to create a view which has two DropDownLists. The options available in the second DropDownList depend upon what the user has selected in the first. I'm passing this data to my view in the ViewBag as follows:
List<SelectListItem> firstBoxChoices = ViewBag.firstBoxChoices;
Dictionary<string, List<SelectListItem>> secondBoxDict = ViewBag.secondBoxDict;
The first object has the choices for the first DropDownList. When the user selects one of those, I need to get the appropriate list of choices for the second DropDownList from my Dictionary. I just can't figure out how to achieve this. If I get the new selection of the first DropDownList in a Javascript onchange() function, there doesn't seem to be any way to use this value as the key for my C# dictionary.
Of course, I've seen this functionality on the web so I know it must be possible somehow. How can I achieve this?
Thanks!
There are a couple ways of doing this without forcing you to store all the possible data items in the model, my preference is to use Javascript/JQuery. Here is an example of a Country/State cascading drop down:
Javascript used to get states when a country is selected:
<script type="text/javascript">
function AppendUrlParamTokens(url, params) {
for (var param in params) {
if (params[param] == null) {
delete params[param];
}
}
return url + "?" + jQuery.param(params);
}
function OnCountriesChange(ddl) {
jQuery.getJSON(AppendUrlParamTokens('#Url.Action("GetStates", "Data")', { countryId: ddl.options[ddl.selectedIndex].value }), function (result) {
var target = jQuery('#states_ddl');
target.empty();
jQuery(result).each(function() {
jQuery(document.createElement('option'))
.attr('value', this.Value)
.text(this.Text)
.appendTo(target);
});
});
};
</script>
Country dropdown:
#Html.DropDownListFor(model => model.Country, new SelectList(Model.Countries, "Value", "Text", Model.PreviousCountrySelected), "(Select One)", new { id = "countries_ddl", onchange = "OnCountriesChange(this)" })
State dropdown:
Html.DropDownListFor(model => model.State,
Model.States != null
? new SelectList(Model.States, "Value", "Text", Model.PreviousStateSelected)
: new SelectList(new List<SelectListItem>(), "Value", "Text"),
new { id = "states_ddl" })
Controller method to retrieve states:
public ActionResult GetStates(short? countryId)
{
if (!countryId.HasValue)
{
return Json(new List<object>(), JsonRequestBehavior.AllowGet);
}
var data = GetAllStatesForCountry(countryId.Value).Select(o => new { Text = o.StateName, Value = o.StateId });
return Json(data, JsonRequestBehavior.AllowGet);
}
The idea is that on selection of dropdown 1 you use ajax to go retrieve your second dropdown's value.
Edit: Forgot to include utility method for constructing urls
The .change event of your first select should populate the second select by calling a server method that returns the option data based on the selected value. Given the following view model
public class MyModel
{
[Required(ErrorMessage = "Please select an organisation")]
[Display(Name = "Organisation")]
public int? SelectedOrganisation { get; set; }
[Required(ErrorMessage = "Please select an employee")]
[Display(Name = "Employee")]
public int? SelectedEmployee { get; set; }
public SelectList OrganisationList { get; set; }
public SelectList EmployeeList { get; set; }
}
Controller
public ActionResult Edit(int ID)
{
MyModel model = new MyModel();
model.SelectedOrganisation = someValue; // set if appropriate
model.SelectedEmployee = someValue; // set if appropriate
ConfigureEditModel(model); // populate select lists
return View(model);
}
[HttpPost]
public ActionResult Edit(MyModel model)
{
if(!ModelState.IsValid)
{
ConfigureEditModel(model); // reassign select lists
return View(model);
}
// save and redirect
}
private void ConfigureEditModel(MyModel model)
{
// populate select lists
model.OrganisationList = new SelectList(db.Organisations, "ID", "Name");
if(model.SelectedOrganisation.HasValue)
{
var employees = db.Employees.Where(e => e.Organisation == model.SelectedOrganisation.Value);
model.EmployeeList = new SelectList(employees, "ID",
}
else
{
model.EmployeeList = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
[HttpGet]
public JsonResult FetchEmployees(int ID)
{
var employees = db.Employees.Where(e => e.Organisation == ID).Select(e => new
{
ID = e.ID,
Name = e.Name
});
return Json(employees, JsonRequestBehavior.AllowGet);
}
View
#model MyModel
....
#Html.LabelFor(m => m.SelectedOrganisation)
#Html.DropDownListFor(m => m.SelectedOrganisation, Model.OrganisationList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedOrganisation)
#Html.LabelFor(m => m.SelectedEmployee)
#Html.DropDownListFor(m => m.SelectedEmployee, Model.EmployeeList, "-Please select-")
#Html.ValidationMessageFor(m => m.SelectedEmployee)
....
Script
var url = '#Url.Action("FetchEmployees")';
var employees = $('SelectedEmployee');
$('#SelectedOrganisation').change(function() {
employees.empty();
if(!$(this).val()) {
return;
}
employees.append($('<option></option>').val('').text('-Please select-'));
$.getJson(url, { ID: $(this).val() }, function(data) {
$.each(data, function(index, item) {
employees.append($('<option></option>').val(item.ID).text(item.Text));
});
});
});

Pass data from one controller action to another view in mvc

I require to pass a variable from one controller action to javascript in another view..
In controller Action A:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
try
{
UpdateModel(res);
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
TempData["Name"] = "Monjurul Habib";
}
return View(res);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(res);
}
}
In another javascript:
function gridA() {
var message = '#TempData["Name"]';
$('#mylabel').text(message);
}
Only Tempdata works But not the first time its working from the second time after iam calling the action controller
I want to temp data to work rom the first time
I want t clear the data after using
If your javascript is inside the same view that takes the ProjectViewModelNew, you can use a different type for your view, for example you can use composition:
public class MyCompositeClass
{
ProjectViewModelNew ProjectViewModel{get;set;};
string Name{get;set;}
}
and then your action method would be:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
var myView = new MyCompositeClass();
try
{
UpdateModel(res);
myView.ProjecViewModel = res;
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
myView.Name= "Monjurul Habib";
}
return View(myView);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(myView);
}
}
and your js would be:
function gridA() {
var message = '#Model.Name';
$('#mylabel').text(message);
}

Categories