Using Url values in JavaScript with ASP.NET MVC - asp.net-mvc

I'm working on an ASP.NET MVC app. A Razor view in the app is loaded by visiting a route that looks like this:
http://localhost:somePort/objects/edit/{id}
The id is optional. When a user visits this view, I initialize a third-party JQuery plugin. I need to get the ID value from the URL and put it into the initialization. If its null, leave it off. If it exists, add it. Currently, I'm trying the following:
$(function () {
var myPlugin = new Plugin("div#myId", {
url: "/api/PostData/#Request.Params["id"]",
init: function () {
// do stuff
}
});
});
Unfortunately, the url always shows /api/PostData/. Its like it doesn't see the ID value in the URL. How do I put that value here?

You could just put the id into your model from your controller. Then you could do this:
$(function () {
var myPlugin = new Plugin("div#myId", {
url: "/api/PostData/#Model.Id,
init: function () {
// do stuff
}
});
});

Related

UmbracoApiController in Plugin Area Not Found

I've created an UmbracoApiController named FormDatasourceController that resides in my plugin area to be used in ajax calls to get or post data.
[PluginController("AreaName")]
public class FormDatasourceController : UmbracoApiController
{
[HttpGet]
public IEnumerable<ICountry> GetAllCountries()
{
return MerchelloConfiguration.Current.MerchelloCountries().Countries;
}
}
and in the cshtml file I have this request
<script type="text/javascript">
$(function(){
$('#sbmtBtn').on("click", function () {
$.get('~/Umbraco/AreaName/FormDatasource/GetAllCountries', null)
.success(function (data) {
alert(data);
})
.fail(function (e) {
alert('failed' + e);
});
});
});
However, I always get error status 404. I tried to EnableCors but with no luck.
Any advise? I'm using umbraco 7
Edit:
For AngularJs controllers/resources in Umbraco, just do this:
change
$.get('~/Umbraco/AreaName/FormDatasource/GetAllCountries', null)
to
$.get('AreaName/FormDatasource/GetAllCountries', null)
That should get your call working. Ignore the ~/Umbraco/ bit.
Your API call should look:
~/Umbraco/AreaName/FormDatasource/GetAllCountries
See "Plugin based controller" at https://our.umbraco.org/documentation/Reference/Routing/WebApi/#plugin-based-controller.
Note, if you had inherited from 'UmbracoAuthorizedApiController' or 'UmbracoAuthorizedJsonController' your api call should be something like this:
~/Umbraco/backoffice/AreaName/FormDatasource/GetAllCountries
For more information, take a look at the bottom of this page in the documentation site under Backoffice Controllers:
https://our.umbraco.org/documentation/Reference/Routing/WebApi/

View content is not displayed correctly after redirected in controller in asp.net mvc

I have a action method in the controller and two views in different language.
public ActionResult Index(Guid id, string languageName)
{
var view = "Welcome_en";
if (languageName == "Spanish")
view = "Welcome_es";
return View(view, model);
}
The default languageName is "English".(In RouteConfig.cs defaults part). So at the beginning, the page is loaded at http://localhost:12091/Some/sssf6bda-9r5e-64d7-9bd2-63c2te616adb.
And I saw the view was Welcome_en.cshtml. in that view I have a dropdown menu for languages to switch active language. I select Spanish then make an ajax call.
$("#Languages").change(function () {
var activeLanguage= $(this).find('option:selected').val();
$.ajax({
url: "/Some/Index",
datatype: "text",
data: { id: '#Model.Guid', languageName: activeLanguage },
type: "POST",
success: function () {
console.log('Success')
}
})
Then I saw the code entered the controller again. The view to be displayed should be Welcome_es.cshtml.
The view Welcome_es.cshtml basically is same as Welcome_en.cshtml. The difference is the content in different language. And I set break points in Welcome_es.cshtml, it did reached. However the final displayed result is still same as Welcome_en.cshtml.
I am not sure why it shows the English view's content, I cleaned the cookies but it is same. Also I set a break point in English page, it didn't go to there when the language was "Spanish".
Your AJAX request is returning your view, but you aren't doing anything with it. If your view is a partial then you can change the success callback in your AJAX call to update the part of the page which the HTML should replace.
$.ajax({
url: "/Some/Index",
datatype: "text",
data: { id: '#Model.Guid', languageName: activeLanguage },
type: "POST",
success: function (html) {
$('.partial').html(html);
}
});
Or if the view is really a full page then don't use AJAX to make the request.
Your current code is making the ajax call, but is not using the response coming from that call.
You should return the partial view result and use that to update the relevant part of your DOM to see the changes. You can do that in the success event of the ajax call
$.ajax({
url: "/Some/Index",
data: { id: '#Model.Guid', languageName: activeLanguage },
type: "POST",
success: function(response) {
$("#someDiv").html(response);
}
});
Assuming you have a div with id someDiv present in your page, the above code will update the inner html of that element with the response coming from your ajax call, which is the html markup generated by the corresponding views (based on the language name you are passing from client side)
I also noticed that you are calling the same action method for your normal page load and the ajax call. In that case, what are you trying to achieve with the ajax call ? You could simply reload the page. No need of ajax.
$(function() {
$("#Languages").change(function() {
var activeLanguage = $(this).val();
window.location.href = "#Url.Action("index","Home")?languageName="
+ activeLanguage +"&id=#Guid.NewGuid()";
});
});
If you are using a page reload, you might want to select the dropdown with the selection from previous page. You may use the Html.DropDownListFor helper with a view model for your page to address this issue.
Add a new property to your view model to store the selected language.
public class YourPageViewModel
{
// Your other existing properties goes here
public string SelectedLanguage { set;get;}
}
Now in your GET action method, you should set the SelectedLanguage property value based on your method parameter.
public ActionResult Index(Guid id, string languageName)
{
var view = "Welcome_en";
if (languageName == "Spanish")
view = "Welcome_es";
var model = new YourPageViewModel();
model.SelectedLanguage = languageName;
return View(view, model);
}
Now in your view, use the DropDownListFor helper method
#model YourPageViewModel
#Html.DropDownListFor(m => m.SelectedLanguage, languages,
new { #class = "form-control" });
Assuming languages is a list of SelectListItem's. Replace it with the collection you have to render the dropdown items.
The helper will render the dropdown with the name and id SelectedLanguage. So make sure you update that in your javasacript as well.
$(function() {
$("#SelectedLanguage").change(function() {
var activeLanguage = $(this).val();
window.location.href = "#Url.Action("index","Home")?languageName="
+ activeLanguage +"&id=#Guid.NewGuid()";
});
});

OnClick event on different things like divs, img and so on then use data from those in controller to do something

I been googling for about two hours and couldn't find anything about it.
What does one use(frameowork or maybe it is already uilt up in mvc) to pass data from VIEW to controller.
For example lets say I have a list of products and I wanna delete it without refreshing a page just by clicking on the thing like <div data="23020id" onclick="doSomething()"></div> and so if I would press on that div, something would happen in controller without refreshing the page.
I don't know how to google it or what should I've been aiming for here.
I've seen that many websites does it but I don't really know what they use and how they do it.
Could someone give me any direction?
Let's start with your example.
lets say I have a list of products and I wanna delete it without
refreshing a page just by clicking on the thing like
<div data="23020id" onclick="doSomething()"></div>
Here it simply means you're calling javascript function doSomething() on click. But you can give Id to that div and perform click on that id.
<div id="test"data="23020id"></div>
Now what could be in the this function?
This function called your controller method via an ajax call, which will send Id to the controller which we need to delete.
javascript code:
$('#test').click(function() {
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:id},
success: function(data) {
// update some DOM element with the result returned by the
// server. So supposing that you have some <div id="someContainer">
// that will contain the part of the DOM you want updated:
},
error: function() {
alert("error");
}
});
});
Now when you click on button, that will call your controller method and pass id.
public ActionResult Delete(int Id)
{
// do delete here.
return Json(data);
}
Perform deletion on method and return view, and update it on ajax success.
I suggest you to use Partial View for such things. For more see here: Rendering a Partial View and JSON Data Using AJAX in ASP.NET MVC
you can try with this
you can not return View() from ajax call. you need to retrun Json()
you Action method
public ActionResult Delete(int Id)
{
// delete method call
return Json("success", JsonRequestBehavior.AllowGet);
}
your ajax call
$("#divId").click(function() {
var dataattr = $(this).attr("data"); //use this variable
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:dataattr },
success: function(data) {
refresh your DOM element
},
error: function() {
alert("error");
}
});
});
you could use JQuery for that..
$("#divId").click(function() {
dataattr = $(this).attr("data"); //use this variable
$(this).hide();
});

How to Prevent Page refresh on select change for dropdownlist in MVC

I have a dropdownlist in my razor view MVC like
#Html.DropDownListFor(n => n.EMP_ID, (SelectList)ViewBag.EmployeeList, new { #id = "ddlemployee" },"---choose an Employee Name--").
I have applied select change event to drop-down using jquery, when select Employee name getting Employee names and realted data, but problem is when i select a value in drop-down, dropdownlist setting again set to default first value,
It is not sticking to particular selected value, in terms of Asp.net terminology, how to prevent postback to dropdownlist?
//Redirected to Controller
<script>
$(document).ready(function () {
$("#ddlemployee").change(function () {
location.href ='#Url.Action("GetEmployeeDetails", "Employer")'
});
});
</script>
//Action Method in Employer Controller
public ActionResult GetEmployeeDetails(Timesheetmodel model)
{
try
{
ViewBag.EmployeeList = objts.getEmployeeNames();
var emps = from n in db.TIMESHEETs
where n.RES_ID == model.EMP_ID
select n;
int count = emps.Count();
foreach (TIMESHEET ts in emps)
{
model.PROJ_ID = ts.PROJ_ID;
model.SUN_HRS = ts.SUN_HRS;
model.MON_HRS = ts.MON_HRS;
model.TUE_HRS = ts.TUE_HRS;
model.WED_HRS = ts.WED_HRS;
model.THU_HRS = ts.THU_HRS;
model.FRI_HRS = ts.FRI_HRS;
model.SAT_HRS = ts.SAT_HRS;
}
}
catch (Exception ex)
{
throw ex;
}
return View("Timesheet", model);
}
ASP.Net Webforms achieve StateFullness by using Some thing called ViewState
It is implemented as hidden fields in the page to hold data between requests.
This way , asp.net webforms achieves post back mechanism and was able to hold values in bewteen the requests.
Since Http is a stateless protocol , which means it has no relation between requests.
View State is absent in ASP.Net MVC.
So, you have to stop postback by partially posting back . Which means that you need to send an asynchronous request with out refreshing whole page.
It is possible by using AJAX. You can either use
MVC Ajax or Jquery Ajax.
By using AJax, we can eliminate the post back and then do the partial post back.
Solution:
$("#dropdownid").change(function(event e)
{
//Make your ajax request here..
});
Hope this helps
Updated:
$("#dropdownid").change(function () {
$.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
url: /*Your URL*/,
success: function (data) {
//do your callback operation
}
});
});
Got it.
Passing Empid as querystring from jquery like:
<script>
$(document).ready(function () {
$("#ddlemployee").change(function () {
debugger;
var empid = $("#ddlemployee").val();
location.href = '#Url.Action("GetEmployeeDetails", "Employer")?empid=' + empid ;
});
});
</script>
and assign "empid " to model "Empid" in Action method before foreach loop like
model.EMP_ID = empid;//in Controller Action Method before foreachloop of my code
// and this model.EMP_ID binded to dropdownlist.
this EMP_ID passes same id to dropdownlist which was selected. Thats it.

$.post() not working if the mvc model view controller has a parameter

I´m new with MVC. I´m using MVC4.
I'm having an issue with a callback. If I alert before and after the post() call both alerts show but the call doesn't fire.
[HttpGet]
[Authorize]
public ActionResult Dashboard(int Menu)
{
//some code
return View("Dashboard");
}
<script>
$(document).ready(function () {
$.post("../Client/GetFact", {},
function (data) {
//some code
});
});
</script>
[HttpPost]
[Authorize]
public JsonResult GetFact()
{
//some code to fill object_data
var data = object_data;
return Json(data);
}
As long as I leave ActionResult Dashboard without a parameter is works. If I add a parameter to Dashboard(int Menu) then the call back to GetFact doesn't work.
I searched and found a similar post and follow the instructions given by you guys, but still does not work( looked at: getJSON not working if the mvc model view controller has a parameter).
I do not know what I'm doing wrong. Can you help? Thank's!
I do something similar with $.get, using jquery with the #Url.Action instead of the url.
in addition to using the FormContext to pass to my Action :
Place just before #using (Html.BeginForm())
#{ ViewContext.FormContext = new FormContext(); }
example :
$.get('#Url.Action("ActionName", "ControllerName")', { IDName: $('#IdName').val() }, function (data) {
//Do Something here with the data
});
I would imagine form post would be
$.post('#Url.Ation("ActionName", "ControllerName")', function (data) {
//Do Something here with the data
});
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: data,
success: success,// -> call alert here
dataType: dataType});

Resources