how to call a controller method in asp.net mvc and show the details in labels in the view - asp.net-mvc-4

I have a view with a text box, when I type and enter a service number then it should retrieve the data from the database and show those in labels in the same view, This application is ASP.net MVC application. Can some one tell me how to do this. Thanks
Further more
can I call controller methods without javascript
Is that possible to call controller methods in view and show the results in the same view
If can the show me how to do it, Thanks

You could use AJAX. Let's have an example:
#Html.LabelFor(x => x.FooBar, htmlAttributes: new { id = "fooBarLabel" })
#Html.TextBoxFor(x => x.FooBar, new { id = "fooBar", data_url = Url.Action("CalculateValue") })
and then in a separate javascript file you could subscribe to the .change event of the text field and trigger an AJAX call to the controller action:
$(function() {
$('#fooBar').change(function() {
var url = $(this).data('url');
var value = $(this).val();
$('#fooBarLabel').load(url, { value: value });
});
});
and all that's left is the corresponding controller action:
public ActionResult CalculateValue(string value)
{
// The value parameter will contain the text entered by the user in the text field
// here you could calculate the value to be shown in the label based on it:
return Content(string.Format("You entered: {0}", value));
}

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.

MVC 4 Dropdownlist form.submit pass in parameter value

I have this dropdown list that I would like it to post back, and pass the id to the controller. This code as it currently is will post back when I change the drop down, but as you can see, there is a hardcoded value of 3 that I am passing in. How do I get the SelectList value of the selected item to pass it to the controller?
#using (Html.BeginForm("Index", "PurchaseOrder", new { id = 3 }))
{
#Html.DropDownList("jobStatuses", (SelectList)null, new { onchange = "this.form.submit();" })
}
I would do it like this:
#using (Html.BeginForm("Index", "PurchaseOrder", new { id = "" }))
{
#Html.DropDownList("id", (SelectList)null, new { onchange = "this.form.submit();" })
}
Changing the name of the control to id will pass it through to the id parameter of the controller action

mvc4 partial view used twice on the same view

I have a partial view for cascading drop downs i.e. Country and State. I am using the following razor view statement to render this partial view
#{Html.RenderAction("PopulateCountriesDropdown", "Helper");}
and it works just fine. Following is the complete code for the partial view that makes an asynchronous call to an action method of the controller
<pre>#model OnlineExamSystem.Models.CountryAndStateViewModel
#Html.LabelFor(m => m.c.CountryName)
#Html.DropDownListFor(m => m.c.CountryId, new SelectList(Model.cntlist, "CountryId", "CountryName"),"--Select Country--", new { #class="aha" })
#Html.Label("State")
Note: since i am unable to write HTML i.e. I have a simple html select for displaying 2nd drop down to show states with class="ddlstates"
<script type="text/javascript">
$(document).ready(function () {
$(".aha").change(function () {
var Url = '/Helper/PopulateStateDropdown';
var catId = $(this).val();
//alert(catId);
var select = $('.ddlstate');
if (catId != '') {
$.getJSON("/Helper/PopulateStateDropdown", { id: catId },
function (ddl) {
select.empty();
select.append($("<option></option>", { value: 0, text: '--Select State--' }));
$.each(ddl, function (index, itemData) {
select.append($("<option></option>", { value: itemData.Value, text: itemData.Text }));
});
});
}
else {
select.empty();
select.append($("<option></option>", { value: 0, text: '--Select State--' }));
}
});
});
as i said this works just fine. but here is the problem i.e. when I try to render the same partial view again on the same page (view) as following
#{Html.RenderAction("PopulateCountriesDropdown", "Helper");}
the rendering is ok, but changing the country in the 2nd partial view does not select the states properly. Also I have noticed that following action method is called twice for the first partial view
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult PopulateStateDropdown(string id)
{
var ls = State.GetStateByCountryId(Int32.Parse(id)).AsEnumerable();
var ddl = ls.Select(m => new SelectListItem() { Text = m.StateName, Value = m.StateId.ToString() });
return Json(ddl, JsonRequestBehavior.AllowGet);
}
and interestingly the the above method is not at all called from the 2nd partial view.
(doucment).ready() binds event to the dome elements when the page is loaded first time, it finds the elements in DOM and bind events to them, in your case as its a partial view, html is rendered dynamically on page after page is loaded so event is not binded.
Use live function for event as you html is dynamically added on the view:
Do like this:
$(".aha").live('change',function () {
});

Kendo Grid Custom comboBox Filter

I has grid which will load data as filterable combo box, So I need to create custom filter for this column with filterable combo box also.
I create combo box and assign it to the column filter UI. My problem is when the combobox read the data from the controller it does not send the filter text to the controller.
<script type="text/javascript">
function outletFilter(element) {
debugger;
element.kendoComboBox({
dataTextField: "OutletNameE",
dataValueField: "OutletID",
autoBind: false,
minLength: 1,
dataSource: {
serverFiltering: true,
transport: {
read: "#Url.Action("GetOutletsCombo")"
}
},
optionLabel: "--Select Value--"
});
}
</script>
#(Html.Kendo().Grid<Spine.ERP.ViewModel.AccountReceivableOutletViewModel>()
.Name("ARDetails_OutletGrid")
.Columns(columns =>
{
columns.Bound(p => p.AccountReceivableID).Hidden();
columns.Bound(p => p.AccountReceivableOutletID);
columns.Bound("Outlet.OutletName")
.EditorTemplateName("OutletForeignKeyEditor")
.ClientTemplate("<a>#=OutletID ##=OutletID? '-' : ' ' ##=OutletID ?
Outlet.OutletName : ' ' #</a>")
.Filterable(filter => filter.UI("outletFilter"));
})
And here are my controller function
public ActionResult GetOutletsCombo(string text)
{
if (text == null)
text = "";
var result = new List<OutletViewModel>();
var Outlets = outletRepository.FilterOnID("Outlet", new string[] { "OutletID", "OutletNameE" }, text).ToList();
result = (from outlet in Outlets
select new OutletViewModel
{
OutletID = outlet.OutletID,
OutletNameE = outlet.OutletNameE,
OutletNameA = outlet.OutletNameA
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
First of all if you perform a "read", it does not send any additional value to the controller so in "public ActionResult GetOutletsCombo(string text)" you wouldn't get any value in "text".
For server filtering you can see kendo's demo on the following page
http://demos.kendoui.com/web/combobox/serverfiltering.html
As far as I get from your question, you want to do a Kendo Grid and on there you want to have a combobox to filter the data in the grid. In this case, you may check the similar kind of demo in Kendo's site
http://demos.kendoui.com/web/grid/toolbar-template.html
For filter menu you can check this on kendo under ASP.NET MVC
http://demos.kendoui.com/web/grid/filter-menu-customization.html
Hope you can work out your problem from these examples. In case you can't then put a comment underneath this post. I shall try again to help you.

Ajax.ActionLink parameter from DropDownList

I have the following view part:
<div class="editor-label">
#Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Type, ElangWeb.Helpers.ModelHelpers.GetExerciseTypes())
</div>
I want to have a link which will generate some partialview based on my model's Type property which is an Enum (I return different partial views based on the type),
I've added the following link:
#Ajax.ActionLink("AddExerciseItem",
"AddExerciseItem",
"Exercise",
new { type=#Model.Type},
new AjaxOptions() { HttpMethod="GET", InsertionMode = InsertionMode.InsertBefore, UpdateTargetId="ExerciseItems"})
My controller action is defined as follows:
public ActionResult AddExerciseItem(ExerciseType type)
{
return PartialView("ExerciseItemOption", new ExerciseItemOption());
}
I however does not work because I have the exeption "Object reference not set to an instance of an object" for my Model. How to resolve this issue?
You could use a normal link:
#Html.ActionLink(
"AddExerciseItem",
"AddExerciseItem",
"Exercise",
null,
new { id = "add" }
)
that you could unobtrusively AJAXify:
// When the DOM is ready
$(function() {
// Subscribe to the click event of the anchor
$('#add').click(function() {
// When the anchor is clicked get the currently
// selected type from the dropdown list.
var type = $('#Type').val();
// and send an AJAX request to the controller action that
// this link is pointing to:
$.ajax({
url: this.href,
type: 'GET',
// and include the type as query string parameter
data: { type: type },
// and make sure that you disable the cache because some
// browsers might cache GET requests
cache: false,
success: function(result) {
// When the AJAX request succeeds prepend the resulting
// markup to the DOM the same way you were doing in your
// AJAX.ActionLink
$('#ExerciseItems').prepend(result);
}
});
return false;
});
});
Now your AddExerciseItem controller action could take the type parameter:
public ActionResult AddExerciseItem(string type)
{
...
}