How to get the drop down value into controller - asp.net-mvc-4

Hi I have a drop down in View and for select index change I am using Jquery like this
$(function () {
$('#IncidentObj').change(function () {
var selectedValue = $(this).val();
alert(selectedValue)
$.ajax({
url: '#Url.Action("Index", "Operation")',
type: 'GET',
cache: false,
data: { value: selectedValue },
success: function (data) {
alert(data.success)
}
});
});
});
How can I get the value of selectedvalue into controller?

To pass the value to the Index action method within your Operation Controller you need to make sure your Index action method within your Operation Controller has a parameter named "value" like so:
public class OperationController{
public ActionResult Index(String value){
// do stuff here with "value"
...
...
}
...
...
}
where the "String" type I specified for the method parameter "value", can be changed to Int, bool, ect.. to fit your needs.
The reason why the method parameter is named "value" and not something else is because in your ajax call you specified:
data: { value: selectedValue },

Related

how to pass value ember view to controller

I am new in pretty ember js development .
I have done view below code
{{view "select" content=model prompt="Please select a name" selectionBinding="" optionValuePath="content.body" optionLabelPath="content.title"}}
using following Json
posts = [{
title: "Raja",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}];
and Router
App.InRoute = Ember.Route.extend({
model: function () {
return posts;
}
});
My Requirement is passing that combo box selected value to controller
App.InController = Ember.Controller.extend({
alert("combobox selected item")
});
And how an i access that value apicontoller in .net mvc 4
public class ValuesController : ApiController
{
string value= combo box selected value
}
Your "select" view's value attribute needs to be bound to a property on the controller:
add the following to your view's attributes: value=selectedItem
In your controller:
Add "selectedItem"
App.InRoute = Ember.Route.extend({
selectedItem: null,
model: function () {
return posts;
}
});
Now your all set to send it to your Api end point. You could create an action handler and make it happen there. Here is a quick example:
App.InRoute = Ember.Route.extend({
selectedItem: null,
model: function () {
return posts;
},
actions: {
submit: function(){
$.ajax('/api/yourEndPoint', {type: 'POST', data: {body: this.get('selectedItem')} })
}
}
});
In your Handlebars template
<button {[action 'submit'}}>Submit</button>
In your .NET API Controller
public IHTTPActionResult Post(string body){
//.NET's Model Binder will correctly pull out the value of the body keyvalue pair.
//Now do with "body" as you will.
}
You should really look into using Ember-Data, it's freaking awesome.
You only need to set the selectionBinding="someModelAttribute" and the two way data binding will take care of setting the selected value on the model.

ASP.NET MVC4 View Model Parameter Null when Posted

I want to use a view model as input to an Edit form. Call it -
public class StudentEditViewModel
{
}
My Edit action method creates the object and passes it to the Edit view, which has #model set to StudentEditViewModel. This works fine - all data is displayed as expected.
BUT, when I post the changes (using ) things fall apart. Here is the skeleton of my action handler:
[HttpPost]
public ActionResult Edit(StudentEditViewModel student)
{
}
The problem is that "student" is null. All the online examples appear to do it this way, but I'm obviously missing something. Can anyone help me out?
I'll be happy to provide more details if necessary. Thanks in advance.
Your StudentEditViewModel needs properties (E.g public string name { get; set;}) because the StudentEditViewModel should have a property basis for it to have a value and in your view, use the basic LINQ syntax
using(Html.BeginForm())
{
#html.TextBoxFor(u => u.name)
<input type="submit"/>
}
Try adding also with a non-Data annotation ActionResult and check out the breakpoints. This was my mistake before when I tried to program. Hope I can help you.
Are you using Explicitly typed View Model? In this case you can do it by jquery as follows:
$("#btnSave").click(function (event) {
event.preventDefault();
if ($("#form1").valid()) {
var formInput = $('#form1').serializeObject();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: 'your controller action url be here',
data: JSON.stringify(formInput)
})
.done(function (data, textStatus, jqXHR) {
showMsg('page-message', 'success', 'Success!', 'The item was saved.');
$('#PriorityDateId').val(data);
window.location.href = 'after save where you want to redirect(give url)';
})
.fail(function (jqXHR, textStatus, errorThrown) {
showResponse('page-message', 'error', 'Error!', jqXHR.responseText);
});
}
});
If need more info, let me know..
Your model should contain some properties like so:
model:
public class StudentEditViewModel
{
//Sample Properties
public string Name{get;set;}
public int Age {get;set;}
}
And your view should look something like this.
#model Nameofyourproject.Model.StudentEditViewModel
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name) // this where you will enter a value for the Name property
#Html.LabelFor(m => m.Age)
#Html.TextBoxFor(m => m.Age) // this where you will enter a value for the Age property
<input type="submit"/> //this will submit the values to your action method.
}
you will be able to get this values now in your action method
[HttpPost]
public ActionResult Edit(StudentEditViewModel student)
{
var name = student.Name;
var age = student.Age;
}

How To pass Id in jQUERY

Want to perform Edit in popup, I have code but its not working
here is my script
$("#mylink").click(function(e) {
var count = 0;
var $dialog = $("<div id='divCreateTask'></div>");
var Id = $(this).data(e);//
url: "TaskTimeSheet/EditTaskPopUp/" + Id //
var url = "EditTaskUrl" + id;var url = '#Url.Action("EditTaskPopUp", "TaskTimeSheet")';
url += '/?Id=' +Id; $("#tab1").load(url);
$dialog.empty();$dialog.dialog({
autoOpen: true,
width: 600,
height: 650,
resizable: false,
modal: true,
open: function (event, ui) {
$(this).load(url);
},
buttons: {
"Cancel": function () {
$(this).dialog("close"); }
});
} });
#Html.ActionLink("Edit", "TaskTimeSheet", new {id="mylink", param = dr["id"].ToString() })
From this link i have to pass id .....
This all is loaded in table Table Each row Have Edit Button ....now ho to pass Id to the querY,..
use an ajax call
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'post',
cache: false,
async: true,
data: { id: "ID" },
success: function(result){
$('.divContent').html(result);
}
});
});
your controller action would be something like
[HttpPost]
public PartialViewResult Action(int id){
var Model = //query the database
return PartialView("_PartialView", Model);
}
This will call your controller, return a partial view and put it into a container with class "divContent". Then you can run your dialog code to pop up the container.
row id update
to get the id of a table row I use this in the row click event
$(this).closest('tr').find('.ID').val(); // or .html() if you have put it in the cell itself
this will get the row that you are on and then find a cell in that row with class ID. Hopefully this helps.

How to pass textbox input value and dropdownlist selected value as input parameters to Controller in mvc4 using jquery?

I need to pass textbox input value and dropdownlist selected value to Controller in MVC4 ????????? For Eg : I have a Form with Textbox and Dropdownlist and a ( PartialView For Webgrid) . When i give datetime input to Textbox and Selected the "DoctorName" in Dropdown . Then i need to pass textbox input value and dropdownlist values as parameters to the controller ??????? My Controller is used to bind the webgrid in PartialView... The Code i tried which is not working......#doctortype is dropdownlist,#AppointmentDate is Textbox input datetime.
jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#doctorType').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { doctorname: $(this).val() }, { AppointmentDate: $('#AppointmentDate').val() }, function (result) {
$('#FilterWebgrid').html(result);
});
});
});
</script>
is not
$.get(url, `{ doctorname: $(this).val() }, { AppointmentDate: $('#AppointmentDate').val() }`, function (result) {
$('#FilterWebgrid').html(result);
});
You are sending two object. You have to send a single object like this:
$.get(url, { doctorname: $(this).val(), AppointmentDate: $('#AppointmentDate').val() }, function (result) {
$('#FilterWebgrid').html(result);
});
2) check the console and network tab and check if there is any error.
3) The value you are passing must be the same type as the parameter expected in the Action
This is just simple method to post data. If your controller returns data back to view, try $.getJSon();
<input type="text" value="doctor name" id="txtDoctor"/>
<select id="ddlDoctor"><option>SomeSelectedData</option></select>
<script>
$(document).ready(function() {
var txtValue = $('#txtDoctor').val();
var ddlValue = $('#ddlDoctor').val();
$.ajax({
url: '/controller/action',
data: { doc: txtValue, name: ddlValue },
traditional: true,
success: function(result) {
alert(result.status);
}
});
});
</script>
to know more about getJSon and JSON Result, check these links.
GetJson with parameters
JSON result in view

Delete method with array type as parameter showing null value

I am calling web-api method delete all with array type parameter, showing the value null. why?
I am passing data like : data: "ArrMenuId"+ JsArrayMenuId,
function performalldeletemenu()
{
if (confirm('Are you sure you want to delete this menu?'))
{
var JsArrayMenuId = new Array();
$("input:checked").each(function ()
{
//console.log($(this).val()); //works fine
JsArrayMenuId.push($(this).val());
});
alert(JsArrayMenuId);
$.ajax({
url: '/api/MenuWebApi/DeleteAllMenu/',
type: 'DELETE',
contentType: 'application/json; charset=utf-8',
data: "ArrMenuId"+ JsArrayMenuId,
success: function (data)
{
if (data.Success == true)
{
//GetMenuList();
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
}
public HttpResponseMessage DeleteAllMenu(Array ArrMenuId)
{
}
Here ArrMenuId is showing null values.
if any one have solution, please let me know.
Try changing
data: "ArrMenuId"+ JsArrayMenuId,
to
data: {ArrMenuId : JsArrayMenuId.join()}
and changing
public HttpResponseMessage DeleteAllMenu(Array ArrMenuId)
to
public HttpResponseMessage DeleteAllMenu(string ArrMenuId)
I don't think javascript array will translate easily into a c# array and by changing it to this you are instead passing a string. Once you have this comma delimited string you can make it into an array in your c#