I am working in MVC (Model View Controller). I want to pass values, view to controller.. I have code but don't know about how get value in controller..
<input name="Players[0].Level" id="Players_0__Level" type="radio" checked="checked" value="#t"><label for="Players_0__Level">#t</label>
script
<script>
$(document).ready(function () {
$("#Players_0__Level").on("click", function () {
location.href = '/SportsDept/Create/' + $(this).find('#Players_0__Level').val();
});
});
</script>
my question is ...
this code is possible to value pass ?
and how to get value in controller ?
Please give a solution...
Regards
-AR
You can use ViewBag to pass value to view from controller:
Consider this:
Your controller:
public ActionResult Index()
{
ViewBag.DateNow = DateTime.Now;
return View();
}
In your view:
#ViewBag.DateNow
I see you use jQuery, so instead of
$(this).find('#Players_0__Level')
try using
$('#Players_0__Level')
change
<script>
$(document).ready(function () {
$("#Players_0__Level").on("click", function () {
location.href = '/SportsDept/Create/?sports=' + $('#Players_0__Level').val();
});
});
</script>
Related
The application is in .Net framework 3.5 and MVC framework 2.0 for .Net framework 3.5. I have a view which in $.post passes parameters. I also need that $.post , passes model values to controller.
In the view below , how do I pass model in the $.post function, so that the controller gets the value of the Textbox. I need the button and not submit button.
The view is:
<div>
<label for ="Name"> Name</label> <%=#Html.TextBoxFor(m => m.Name) %>
<select id ="prod" style ="width:150px">
<option value ="GL">GL</option>
<option value = "Property"> Property</option>
<option value = "Package">Package</option>
<option value = "Island">Island</option>
</select>
<input type="button" id="btnPost" value = "GetValue" />
</div>
<script src="/Scripts/jquery-1.4.1.min.js" type ="text/javascript"></script>
<script type ="text/javascript" >
$(function() {
$("#btnPost").click(function() {
alert("here" + $("#prod").val());
$.post("/Transfer/DisplayText", { "str1": $("#prod").val()},
function(data) {
alert("success");
});
});
});
Th controller is:
[HttpPost]
public ActionResult DisplayText(string
str1,TestPost_AjaxMVC.ViewModels.TransferViewModel model)
{
string str2 = str1;
return View("Transfer");
}
The model is :
public class TransferViewModel
{
public string Name { get; set; }
}
I think everything is ok in your code just replace
$.post
to $.get
Because you are returning a view from your controller also use Url.action
like below because it may not work when you publish the project
$.get('<%=Url.Action("DisplayText","Transfer")%>', { str1: $("#prod").val()},
function(data) {
alert("success");
});
You should remove double quote from str1.Let me know if it does not work.
JSON.stringify the model and send it as part of data and let MVC use JSON Model Binding
$(function() {
$("#btnPost").click(function() {
var TransferViewModel={};
TransferViewModel.Name="SomeData";
var postData={};
postData.str1=$("#prod").val();
postData.model=TransferViewModel;
$.ajax({
url:"/Transfer/DisplayText",
type:"POST",
data:JSON.stringify(postData),
contentType:"application/json; charset=utf-8",
success: function(){
}
});
});
});
I have a question regarding the calling method from view.
Basically on my view I have 2 links:
1 link : When I click on it, some method should be called and executed, but nothing should change on webpage, so no postback.
2 link: When I click on it, some method should happen and postback can happen, on the same page
In controller I have:
public ActionResult FirstMethod(){ return View();}
public ActionResult SecondMethod(){ return View();}
In view:
#Html.ActionLink("Action 1", "FirstMethod", "Controller");
#Html.ActionLink("Action 2", "SecondMethod", "Controller");
So when I click on both action happens but then i get an error saying cannot find FirstMethod.chtml ..
So is this possible to have one method with postback and another one without? And how to return to the same page ... and not try to get FirstMethod.chtml ..
Following solution is based on AJAX -
Controller -
public class DemoController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult CallMe()
{
return new ContentResult() { Content = "This is Demo " };
}
}
Index.cshtml -
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Click").click(function () {
$.ajax({
url: "/Demo/CallMe",
type: "GET",
error: function (response) {
alert(response);
},
success: function (response) {
alert(response);
}
});
});
})
</script>
<input type="button" value="Click" id="Click" />
First navigate to /demo/Index, that will display the page with above markup with a button in the page. And when we click on the Click button, we have -
The #Html.ActionLink method basically just forwards you to the specified controller-action, you cannot change this, since this is the purpose of the method.
You have to handle the click client-side, and bind a specific action to it (post some data to a url, and do nothing afterwards). One fairly easy way to do this, is to use jQuery.Post
Example from the above jquery link.
Example: Request the test.php page, but ignore the return results.
$.post("test.php");
Actually, there is no postback concept in asp.net mvc. all interactions with server should via the controller/action.
#Html.ActionLink() method just generate a link(tag a in html) and do nothing. everything happens after you send a request(such as click the link) to controller/action, if you want do nothing when click the link, you'd better use AJAX method like this
#Html.ActionLink("Action 1", "FirstMethod", "Controller", null/*routeValues*/, new { id = "link1Id" });
<script type="text/javascript">
$(function () {
$("#link1Id").click(function () {
$.get("/Contoller/FirstMethod", function () {
//do nothing or alert(something)
});
return false;
});
})
</script>
You can simply return another view after you've done what you wanted in your controller action:
public ActionResult SecondMethod()
{
//do something
return View("FirstMethod");
}
After you've seen this you will most probably be disgusted by the use of magic strings to reference views or controllers and that disgust is completely understandable :)
Then you should look whether something like T4MVC could fit your needs.
I need to be able to populate data into a <div> or some other sort of section from an object after the corresponding string has been selected from a drop down list (lazy loading).
When a chnage is made in the dropdownlist, I want the method in my controller to be called which will fill in <div id=result></div> with the output from the method.
Perhaps I am approaching this problem wrong.
I suspect the problem is in my JavaScript.
Here is my approach:
View:
<div>#Html.DropDownList("MyDDL") </div>
<br>
<div id="result"></div>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = "";
$("#MyDDL option:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "HomeController/showInfo";
//I suspect this is not completely correct:
$.post(url, {str: strSelected},function (result) {
$("result").html(result);
});
});
});
</script>
Controller (Perhaps I shouldn't be using PartialViewResult):
public ActionResult Index()
{
List<string> myList = new List<string>();
List<SelectListItem> MyDDL = new List<SelectListItem>();
myList.Add("Tim");
myList.Add("Joe");
myList.Add("Jim");
//fill MyDDL with items from myList
MyDDL = myList
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
ViewData["MyDDL"] = MyDDL;
return View();
}
[HttpPost]
public PartialViewResult showInfo(string str)
{
Person p = new Person(str); //name is passed to constructor
p.LoadInfo(); //database access in Person Model
ViewBag.Info = p.Info;
return PartialView("_result");
}
_result.cshtml:
<p>
#ViewBag.Info
</p>
Thanks You.
Change your script a little bit. Missing a # in the jQuery selecter for result div . Use the code given below
$.post(url, {str: strSelected},function (result) {
$("#result").html(result);
});
In my opinion if the javascript are in local don't need put $.post(url, {str: strSelected},function (result) {
You can use
//I suspect this is not completely correct:
$("#result").html(result);
try it
Did you try debugging p.LoadInfo() if it has any value? I also have some suggestions for your script:
Try adding keyup in your event so you can get the value in cases when the arrow keypad is used insted of clicking:
$("#MyDDL").on("change keyup", function () {
// you can get the dropdown value with this
var strSelected = $(this).val();
So I made the following changes and it worked:
View:
<div><%= Html.DropDownList("MyDDL") %> </div>
<br>
<span></span>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = $("#MyDDL option:selected").text();
var url = "/Home/showInfo";
$.post(url, {str: strSelected},function (result) {
$("span").html(result);
});
});
});
_result.cshtml:
#ViewBag.Info
The Controller was left unchanged.
Ey!
How I could refresh a Partial View with data out of the Model?
First time, when the page loads it's working properly, but not when I call it from the Action.
The structure I've created looks like:
Anywhere in my View:
#{ Html.RenderAction("UpdatePoints");}
My PartialView "UpdatePoints":
<h3>Your points are #ViewBag.points </h3>
At the Controller I have:
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
Thanks for your help!
UPDATE
Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
#Html.Hidden("newpoints", Model)
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button').on("click", function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.target').load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
You can also try this.
$(document).ready(function () {
var url = "#(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
setInterval(function () {
var url = "#(Html.Raw(Url.Action("ActionName", "ControllerName")))";
$("#PartialViewDivId").load(url);
}, 30000); //Refreshes every 30 seconds
$.ajaxSetup({ cache: false }); //Turn off caching
});
It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.
In the controller section you can update the object and pass the object to the partial view.
public class ControllerName: Controller
{
public ActionResult ActionName()
{
.
. // code for update object
.
return PartialView("PartialViewName", updatedObject);
}
}
Thanks all for your help!
Finally I used JQuery/AJAX as you suggested, passing the parameter using model.
So, in JS:
$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");
In Controller:
var model = _newPoints;
return PartialView(model);
In View
<div id="divPoints"></div>
#Html.Hidden("newpoints", Model)
Controller :
public ActionResult Refresh(string ID)
{
DetailsViewModel vm = new DetailsViewModel(); // Model
vm.productDetails = _product.GetproductDetails(ID);
/* "productDetails " is a property in "DetailsViewModel"
"GetProductDetails" is a method in "Product" class
"_product" is an interface of "Product" class */
return PartialView("_Details", vm); // Details is a partial view
}
In yore index page you should to have refresh link :
Refresh
This Script should be also in your index page:
<script type="text/javascript">
$(function () {
$('a[id=refreshItem]:last').click(function (e) {
e.preventDefault();
var url = MVC.Url.action('Refresh', 'MyController', { itemId: '#(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name
$.ajax({
type: 'GET',
url: url,
cache: false,
success: function (grid) {
$('#tabItemDetails').html(grid);
clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
}
});
});
});
This is driving me crazy. All I'm trying to do is to pass in a Id to a ActionMethod which is working and have an Object be returned to the javascript. Then in javascript, I want to be able to say something like..Objec.Property, ie/ Student.Name, or Student.GPA.
Any help is appreciated. I tried json but couldn't get that to work either.
ActionResult:
[AcceptVerbs(HttpVerbs.Get)]
public Epic GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id));
return Epictemplist.SingleOrDefault();
}
javascript:
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result);
});
});
});
</script>
result.Name is obviously wrong I just dont know how to call this the right way.
Tman, I had a similiar issue that Darin helped me with. I needed to add a $.param to my getJSON. Check out this post MVC ListBox not passing data to Action
try changing your method like this
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id)).SingleOrDefault();
return Json(Epictemplist, JsonRequestBehavior.AllowGet);
}
Than from your JS
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result.Name);
}, 'json');
});
});
</script>