I have a javascript function that calls a MVC action result which in turn will populate the correct View. I need to pass .Net code with that pop up call, is it possible?
So for example I need to pass a integer from the model over so I can use it in my action result.
a button click calls this function
ShowPopUp = function () {
window.showModalDialog("/FileUpload/GetPopupData", "wndPopUp", "width=300,height=500");
}
and here is the action result
public ActionResult GetPopupData()
{
//Call the pop up view and populate it accordingly
return new GetDocumentTypeAction<ActionResult>
{
OnLoaded = m => View("../../Areas/Exports/Views/FileUpload/FileUpload", m),
OnErrorOccured = (m) => Redirects.ToErrorPage()
}.Execute(GtsClient);
}
How will I send the int over and how will I read it in the action result?
In your view, render out the integer you want from the model as a JavaScript variable that you can reference in your ShowPopUp() function.
<script>
var viewId = <%=Model.ViewId%>;
ShowPopUp = function () {
window.showModalDialog("/FileUpload/GetPopupData/" + viewId,
"wndPopUp", "width=300,height=500");
}
</script>
Related
I have a .net MVC Project. I assigned a List to a session variable. And in the View, i use jquery to iterate the data in the session variable.
ie,
var doctors = #Html.Raw(Json.Encode(HttpContext.Current.Session["DoctorList"]));
doctorCount = doctors.length;
for(i=0;i<doctorCount ; i++)
{
var totalinvoice =0;
rows = "<tr><td style='text-align:center'>"+ (parseInt(i, 10)+1) +"</td><td colspan='6'><b>" + doctors[i].D_Name + "</b></td></tr>"
$(rows).appendTo("#tbl_doctorwise tbody");
}
This code some time gives null even if the session variable contains list value. But sometimes it works.
Is there any other method to loop a session variable in the mvc view (jquery)?
how I get the session value in jquery ??? ( session variable contains list )
If you are making an ajax call and setting this session item in your action method, it won't available in your original view as that view code was already executed when you requested the action method for that view.
What you should do is, instead of setting this data in session, return that as json from your action method.
[HttpPost]
public ActionResult GetDoctorwiseReport(DateTime fromDate,DateTime toDate)
{
var doctorList = new List<Doctor>();
//populate this list now
return Json(doctorList);
}
and now in your ajax call's success handler will receive this data and you can loop through them.
success: function(data) {
$.each(data,function(ind,item)
{
//build your html here as needed.
console.log(item);
});
}
<script>
$(function ()
{
var doctors= #Html.Raw(Json.Encode(HttpContext.Current.Session["DoctorList"]))
$.each(doctors, function (index, value)
{
var totalinvoice =0; rows = "<tr><td style='text-align:center'>"+ (parseInt(i, 10)+1) +"</td><td colspan='6'><b>" + value.D_Name + "</b></td></tr>"
$(rows).appendTo("#tbl_doctorwise tbody");
})
});
</script>
How can I update a dropdownlist in MVC3. I want to refill it with latest data filled by some other view, but I do not want to postback the view and want to achieve it with jquery.
I have a dropdownlist like:
#Html.DropDownListFor(m => m.Department, Model.Departments)
#Html.ValidationMessageFor(m => m.Departments)
<input type="button" value="Refresh" id="btnrefresh" />
I have written jquery code to call controller's method:
$("#btnrefresh").click(function () {
var ref = '#Url.Action("RefreshDepartments")';
var model = '#Model.ToJson()';
var data = { empModel: model };
$.getJSON(ref, data, function (result) { alert(result.message); });
return false;
});
And Here is the controller method:
public ActionResult RefreshDepartments(EmployeeModel empModel)
{
empModel.Departments = GetDepartments();
empModel.Roles = GetRoles();
return Json(new { message = "Updated successfully"}, JsonRequestBehavior.AllowGet);
}
How can I update the dropdownlist with latest values on clicking "Refresh" button without any postback?
Is it a good idea to pass the model to the controller and update the model properties? What other ways are possible ?
It doesn't look to me like you need the model to be posted to your controller for what you're doing. In addition, yes, you absolutely can do this with jquery! On a side note, you could also do it with an Ajax.BeginForm() helper method, but lets deal with your jquery example.
Rather than complexify your jquery with your #Url.Action, you can simply call the path itself.
$("#btnrefresh").click(function () {
var ref = 'ControllerName/RefreshDepartments';
$.each(result, function (index, val) {
$('#whateverYourRenderedDropdownListHtmlObjectis')
.append($("<option></option>")
.attr("value", val.Text)
.text(val.Text));
});
});
Now, for your controller...
public JsonResult RefreshDepartments()
{
return Json(GetDepartments, JsonRequestBehavior.AllowGet);
}
private SelectList GetDepartments
{
var deparments = GetDepartments;
SelectList list = new SelectList(departments);
return list;
}
This is an alternative to returning the model. It allows you to manipulate the raw JSON instead. Hope it helps!
You almost did it all! Why don't you send the data, I mean list, by RefreshDepartments action? You sent a message to view, so you can send the list similarly and instead of alerting the result you can fill the dropdownlist. something like this:
public ActionResult RefreshDepartments(EmployeeModel empModel)
{
return Json(new { departments = GetDepartments()}, JsonRequestBehavior.AllowGet);
}
$.getJSON(ref, data, function (result) {
$("#Department").html("");
for (var i = 0; i < result.departments.length; i++) {
var item = result.departments[i];
$("#Department").append(
$("<option></option>").val(item.Id).html(item.Name);
);
});
});
I would like to pass a javascript variable in a #Url.Action method as a route parameter.
I like to pass the screenmode javascript variable as a route parameter to my action method.
I have a view model with ScreenMode enum property and based on it i
should call a action in Ajax. I also need to pass a javascript
variable as a parameter for route.
This is what i tried and got compilation error.
The name 'screenMode' does not exist in the current context
$("#role-detail-form").submit(function (e) {
if ($(this).valid()) {
var screenMode = 0;
#{
if (Model.ScreenMode == UI.ViewModel.ScreenMode.New)
{
<text>
screenMode =2;
</text>
}
}
$.post('#Url.Action("SaveRoleDetail", new { mode=screenMode})',
$(this).serialize(), function (data) {
$("#role-detail").html(data);
$.validator.unobtrusive.parse($("#role-detail"));
});
}
e.preventDefault();
});
My Action is
public ActionResult SaveRoleDetail(RoleModel viewModel, ScreenMode screenMode)
{
}
You'd have to split that out and build the query string yourself, in order to incorporate the Javascript variable.
Something like this is what you need:
$.post('#(Url.Action("SaveRoleDetail"))?screenMode=' + screenMode)
EDIT: Although probably best practice, you should store the ScreenMode variable in your Model, then put a HiddenFor in your view for it. Then, whenever you change the value in Javascript, simply update the value of the hidden input, that way your action method only needs to take the view model as a parameter. If you are posting the form in JavaScript and you can call $("#form").serialize() to send all the data back within your post call.
Also it's possible to create a place holder and then replace it:
var url = '#Url.Action("GetOrderDetails", "Home", new { id = "js-id" })'
.replace("js-id", encodeURIComponent(rowId));
If you use T4MVC and jQuery, you can call the ActionResult doing the following:
In the controller:
public ActionResult SaveRoleDetail(RoleModel viewModel, ScreenMode screenMode)
{
}
In the view:
$.post("#Url.Action(MVC.Home.SaveRoleDetail())", { viewModel: param1, screenMode: param2) }, function (data) {
//Do Work
});
Access your route values (perhaps in html.HiddenFor). Values from JavaScript and Build your URL without #Url.Action. Use the URL to post.
I've a method in a NamesModel which fetches all the names and returns a list of names:
public static List<NamesModel> GetAllNames()
{
List<NamesModel> names = new List<NamesModel>();
//
// code to fetch records
//
return names;
}
In my controller:
public ActionResult Index()
{
NamesModel model = new NamesModel();
model.GetAllNames();
return View(model);
}
In the view, I've got a textbox:
#Html.TextBox("search-name")
Now in my javascript, I want to fetch all names into a variable either from a model (from method) or from controller, for example:
<script type="text/javascript">
$(function () {
var names = ...........
$(document).ready(function () {
$('#search-name').autocomplete({
source: names
});
});
});
</script>
If I use hardcoding then it works but I want to use the names stored in the db. Is it possible?
hardcoding example:
var names = ["abc", "xyz"];
You could use Ajax and Json for this
For your controller:
[HttpPost]
public JsonResult GetAllNames()
{
List<NamesModel> names = new List<NamesModel>();
//
// code to fetch records
//
return Json(names);
}
Or for debugging so you can view the json in browser:
public JsonResult GetAllNames()
{
List<NamesModel> names = new List<NamesModel>();
//
// code to fetch records
//
var result = Json(names);
result .JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result ;
}
(note this is actually jquery but since you use document.ready you've allready included jquery)
in your javascript make a call to the method above:
$.getJSON(#Url.Content("~/ControllerName/GetAllNames/"), function (result) {
var ListWithNames = data;
});
The "source" options property can be a string wich points to the URL which return json data (http://api.jqueryui.com/autocomplete/#option-source)
The best solution to my problem is in this blog: http://theycallmemrjames.blogspot.co.uk/2010/03/jquery-autocomplete-with-aspnet-mvc.html
Thanks to everyone who tried to help me.
I have created a dropdownlist on the view and showing a list.
#Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"))
I want to refresh the page when the user selects the value from the drop down.
I don't know how to map the selection event from dropdown to a controller function without clicking any button.
On the view load there is a controller function which is populating the view with the list.
public ActionResult Populate()
{
List<string> list = get it from sql server
ViewModel viewModel = new ViewModel();
viewModel.list = list;
return view();
}
But how do you call a controller function which will take the selected value as an Id and retrieves the data and refreshes the page with the result.
You can't do it without javascript help. Just bind on select event and send the form or make an ajax request.
using jQuery:
$('#yourDropDownId').change(function(){
$('#yourFormId').submit();
});
or if you need ajax call insted of submit use $.post or $.get.
Add this to your layout in the head:
<script type="text/javascript">
$(document).ready(function () {
$('select:[autopostback=true],input[type=checkbox]:[autopostback=true],input[type=radio]:[autopostback=true]').live('change',function () {
$(this).closest('form').submit();
});
});
</script>
in your view:
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"), new { autopostback = "true" })
}
The form that your dropdownlist is in will get submitted when you change selection of your dropdownlist. If the result of the action of that form is the same page, it will be reloaded with whatever stuff being updated
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
or
<%=Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"), new { onchange="this.form.submit();" })%>
It's simple. In your javascript you have:
$(document).ready(function () {
$('#SelectedId').change(function () {
var id = $(this).val();
$.getJSON("/YourController/YourAction", { id: id},
function (data) {
$("#SomeDivSelector").html(data);
});
});
});
Your controller should look like:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult YourAction(int id)
{
//do something
return Json(ControlToString("~/Views/YourController/YourView.cshtml", yourModelWithData), JsonRequestBehavior.AllowGet);
}
And ControlToString is defined:
private string ControlToString(string controlPath, object model)
{
//CshtmlView control = new CshtmlView(controlPath);
RazorView control = new RazorView(this.ControllerContext, controlPath, null, false, null);
this.ViewData.Model = model;
using (System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter()))
{
control.Render(new ViewContext(this.ControllerContext, control, this.ViewData, this.TempData, writer), writer);
string value = ((System.IO.StringWriter)writer.InnerWriter).ToString();
return value;
}
}
Regards.
What you want to apply, against the concept of the technology you're using.
MVC based on ASP.NET technology, but another way executing. MVC not use better of life cycle of ASP.NET, so, does not "Postback". MVC - in the root based on architectural pattern, that allows to separate the different layers of any system, therefore approach to the development on current technology is completely different. learn more about MVC: http://www.asp.net/mvc
if you want still implement your problem you can use ASP.NET concept and use AutoPostback property of DropDownList control.