I'm working with an ASP.NET mvc projekt and I'm familiar with the usual razor helpers #Html.TextBoxFor... etc. but I'm in the situation where I need to set a string value in the model using a dropdown list, the list always has the same twelve items in it and I just need to populate this list with those items and make sure it sets the field value in the model to the selected one.
I'm curious how I should go about doing this? I've looked at dropdown tutorials and I might be able to get a dropdown working but I'm not sure how to set the field value and I'm not sure where to store these twelve strings. I thought about hardcoding them instead of putting them in a db or something since it's so few but I'm open to better suggestions.
Any help is appreciated
UPDATE
This is my Razor code, I created a simple viewmodel which contains the list of items to display in the dropdown and including the model class I wanna use for this create view.
#Html.DropDownListFor(x => x.question.QuestionId, new SelectList(Model.AreasList), new { #class = "dropdown" })
This is my viewmodel
public class CreateQuestionViewModel
{
public Question question { get; set; }
public IEnumerable<String> AreasList = new List<String> { "Option 1", "Option 2" };
}
It works but I can't figure out why visual studio keeps throwing me a null reference and points at my razor code for the dropdown?
sure, so you need to set the model field based on the selected List Item when the user selects it, assuming that you have a static dropdown list:
//this is your view View1.chtml
#model Class1
<select id="list1" name="list1">
<option value="0">option1</option>
<option value="1">option2</option>
</select>
<script>
$(document.ready)(function(){
//set the list from model
var modelvalue = '#Html.Raw(Json.Encode(Model.ValueFromList))';
$(#list1).val(modelvalue);
});
//handle the change event of Dropdown list
$("#country").change(function()
{
var _selected = $("#list1").val();
var options =
{
type: "POST",
url: '#Url.Action("Action1","controller1")',
data: _selected + ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//set the returned value as the selected dropdownlist value
$(#list1).val(msg);
}
}
};
.ajax(options);
</script>
//this is the class that you want to set the value in (the Model)
Class1
{
public string ValueFromList {get;set;}
}
//then you need an action method ( in your Controller) that will update the Model with the new Value:
public Controller1
{
[HttpPost]
public JsonResult Action1(string value)
{
Class1 cl1=new Class1();
cl1.ValueFromList=value;
return Json(new {Success="true", cl1});
}
Related
I am trying to populate a Kendo mvcGrid and I keep getting the error An item with the same key has already been added.
I have seen elsewhere that duplicate model properties is the likeliest source of the problem but I have no duplicate properties in my model. I've even simplified everything to just a basic mock up to eliminate as many possible variables as possible..and I cant get the grid to load data.
I've tried it as a Html.Partial where its not loaded initially because of a empty model and then loading it through jquery...Ive tried with passing in am empty model so that the grid will load initially without data and then doing a datasource refresh...no luck there either. Basically as soon as I try to add content to the grid with a populated model I get the error and no data is loaded.
Been fighting this issue for 2 days now and had no luck. Ill post my code here maybe someone else can see what I'm missing.
One variable that cant change is the grid resides on a partial view with a model different from its parent view.
in the parent view I have tried both
<div id ="columnkgrid">#{Html.RenderPartial("Columns", new TestFieldIssue.Models.FieldListModel());}</div>
and
<div id="columnkgrid">#Html.Partial("Columns", new TestFieldIssue.Models.FieldListModel())</div>
either way will succeed in posting a grid with no data..it has no data yet because its populated by the selection of a value in a dropdown list.
so as to not over complicate the sample I've just set a hard coded value in the jquery function I have been using to refresh the grid.
function loadgrid() {
var grid = $("#grid").data("kendoGrid");
var val = 1;
grid.dataSource.read({ table_pk: val });
grid.refresh();
}
the grid code in the partial once again kept it simple without any bells and whistles just to test.
#(Html.Kendo().Grid(Model.fields)
.DataSource(data => data
.Ajax()
.Model(model => model.Id(m => m.field_pk))
.Read(r => r.Action("Columns","Home"))
)
.Name("grid")
.Columns(c =>
{
c.Bound(m => m.field_name).Title("Field Name").Width(100);
})
)
and the controller methods loading some mock data
public ActionResult Columns(int? table_pk)
{
FieldListModel model;
if (table_pk == null)
{
model = GetEmptyColumns();
}
else
{
model = GetColumns();
}
return PartialView("Columns", model);
}
public FieldListModel GetColumns()
{
FieldListModel model = new FieldListModel();
model.fields = new List<FieldModel>();
model.fields.Add(new FieldModel { field_name = "field1", field_pk = 1 });
model.fields.Add(new FieldModel { field_name = "field2", field_pk = 2 });
model.fields.Add(new FieldModel { field_name = "field3", field_pk = 3 });
return model;
}
public FieldListModel GetEmptyColumns()
{
FieldListModel model = new FieldListModel();
model.fields = new List<FieldModel>();
model.fields.Add(new FieldModel { field_name = "", field_pk = 0 });
return model;
}
and a very simple Model
public class FieldListModel
{
public List<FieldModel> fields { get; set; }
}
public class FieldModel
{
public int field_pk { get; set; }
public string field_name { get; set; }
}
I made few changes to run your code (correct version of Kendo and JQuery). May be those related to setup at my machine. I was able to reproduce the problem.
Then I changed the action code and was able to see the values populated in Grid:
public ActionResult Columns(int? table_pk, [DataSourceRequest] DataSourceRequest request)
{
FieldListModel model;
if (table_pk == null)
{
model = GetEmptyColumns();
}
else
{
model = GetColumns();
}
return Json(model.fields.ToDataSourceResult(request));
}
The change is accepting an additional parameter in action method of type DataSourceRequest. The Kendo grid wraps request in this object to specify sorting and paging information. The grid itself gets updated with data wrapped under DataSourceRequest object (note in return statement). More information here.
I have 3 tables country , state , city .
I want cascading drop down list as usual.
How can i do that without using the LINQ.
I don't know that how to start. I want to do that using RAZOR. It is okay if it is in JQUERY or JSON.
How to start that.
Thanks in advance.
Can i do that using stored procedure.
tables are:-
user:
name
cityid
country:
id stateid name
state
stateid cityid name
city
cityid name .
i have tried nothing because i don't know where to start.
A general approach to creating cascading selects
Create a view model containing the properties you want to display, including properties for the country and state ID's and a SelectList for the Country options
In your view render selects using #HtmlDropDownFor() for the Country, Sate and Property ID's (the Country select will be populated; the others will be empty)
Using jQuery, in the Country change event, use an AJAX call to an action method which returns a list of States based on the selected Country (either return html to replace the City select, or return JSON to create a new set of option elements.
Repeat the above when a State is selected (to populate the City select)
No one here will provide you complete code like you are asking in your question but usage of dropdown i m explaining below :
Basic and cleanest way to make a dropdown in MVC is like :
Model :
public List<SelectListItem> ItemTypes { get; set; }
public int ItemVal { get; set; }
In your [HttpGet] Controller just bind `Model.ItemTypes` with values
View:
#Html.DropDownListFor(m => m.ItemVal , new SelectList(Model.ItemTypes , "Value", "Text"), " -----Select List----- ")
here in above example the 3rd overload of DropDownListFor() i.e. " -----Select List----- " will be the initial selected item of your dropdown with value equal to ' '.
At Controller during POST ItemVal will have selected dropdown value.
The above shown code is best and simplest way to bind Dropdownlist in MVC.
See this exmple. You'll have an idea. I'm just showing sample which is not tested.
public ActionResult Index()
{
var countries = new List<string> { "USA", "India" };
ViewBag.Countries = new SelectList(countries);
return View();
}
public ActionResult GetStates(string country)
{
//perform filter here based on country
return Json(new[] {
new { Id = 1, Value = "State 1" },
new { Id = 2, Value = "State 2" },
new { Id = 3, Value = "State 3" },
}, JsonRequestBehavior.AllowGet);
}
View Page
<div>Select country:</div>
<div>#Html.DropDownList("country",
ViewBag.Countries as SelectList,
"Please select",
new { id = "country" })
</div>
<div>Select state:</div>
<div>
<select id="state"></select>
</div>
On Country selection, do ajax call and get related states.
<script type="text/javascript">
$(function () {
$('#country').on('change', function () {
$.getJSON('#Url.Action("GetStates")', function (result) {
var ddl = $('#state');
ddl.empty();
$(result).each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
});
});
})
</script>
I have a form where I have a bunch of textbox and dropdowns. I now need to add another array of sub objects and include that as part of the my form post.
I was going to hand roll this as an html table but i thought that i could leverage jqGrid. What is the best way I can use jqGrid locally to add data and then have that included in the form post? The reason that i need jqGrid to act locally is that these are subrecords as part of the larger form so I can't post the jqGrid rows until the larger form is posted (so i have an Id to join these rows with)
So for example, if my post was an Order screen (with textboxes for date, instructions, etc) and now i want to have a grid that you can add products into the order. You can have as many rows as you want . .)
my backend is asp.net-mvc if that helps with any suggestions.
If you use form editing you can extend the postdata in many ways. The most simple one is the usage of onclickSubmit callback:
onclickSubmit: function (options, postData) {
return {foo: "bar"};
}
If you use the above callback then the data which will be post to the server will be extended with the parameter foo with the string value "bar".
Another possibility is the usage of editData option of editGridRow. The best way is to use properties of editData defined as function. In the way the funcion will be called every time before posting of data.
For example the following code
$("#grid").jqGrid("navGrid", "#pager", {}, {
editData: {
foo: function () {
return "bar";
}
},
onclickSubmit: function (options, postData) {
return {test: 123};
}
});
will add foo=bar and test=123 to the parameters which will be send to the server.
The next possibility will be to use serializeEditData. The callback gives you full control on the data which will be sent to the server.
I am using the method of serialization as Oleg suggested.
view
$( "#Save" ).click( function ( e )
{
e.preventDefault();
var griddata= $( "#list" ).getRowData();
var model = {
grid: griddata
};
var gridVal = JSON.stringify( model );
//Now set this value to a hiddenfield in the form and submit
$('#hiddenGridDta').val(gridVal );
$( 'form' ).submit();
});
And in the controller, deserialize the values using Newtonsoft.json.jsonconvert().
public ActionResult SaveTest(TestClass test)
{
testViewModel myGrid = JsonConvert.DeserializeObject<testViewModel>(test.hiddenGridDta);
................
}
testViewModel class
public class testViewModel
{
public IEnumerable<TestGrid> grid { get; set; }
}
TestGrid class
public class profileGrid
{
//fields in the jqgrid (should use the same name as used in *colModel:* of jqgrid)
public int x
{
get;
set;
}
public int y
{
get;
set;
}
.......
}
I'm trying to set the selected Value for a drop down list.
In Controller I have
ViewData["productType"] = new SelectList(myDropDownList);
And in the View:
<%= Html.DropDownList("productType", ViewData["productType"] as SelectList, "defaultValue")%>
So far So good, but the problem is that now I have "defaultValue" twice in my drop down list. so I have all my values in dropdownlist including the "defaultValue". but this code will add the "defaultValue" as the first element. and I see two samples of it.
I like to set the selected valiue to "defaultValue" without adding it twice.
I tried
ViewData["productType"] = new SelectList(myDropDownList, "defaultValue" );
but it didn't work.
Can anyone please tell me what to do?
You should not be using the same name as first argument for the dropdown as the second one. In your example you have used productType for storing both the selected value and the list of available values. In order to render a DropDown in ASP.NET MVC you need 2 properties:
<%= Html.DropDownList(
"selectedProductType",
ViewData["productType"] as SelectList,
"defaultValue"
) %>
and inside your controller action you could set those 2 properties:
ViewData["selectedProductType"] = "abc";
ViewData["productType"] = new SelectList(myDropDownList);
this assumes that you already have an element with value="abc" inside your dropdown list of product types. The value will then be automatically preselected.
I would recommend you an alternative approach though for rendering dropdown lists. It consists of getting rid of view data and introducing view models and using the strongly typed version of the helper:
public class ProductViewModel
{
public string SelectedProductType { get; set; }
public IEnumerable<SelectListItem> ProductTypes { get; set; }
}
then you will have a controller action that will populate this view model and pass it to the view:
public ActionResult SomeAction()
{
var model = new ProductViewModel();
// preselected an element with value = "type2"
model.SelectedProductType = "type2";
// bind the available product types
model.ProductTypes = new SelectList(
// Obviously those could come from a database or something
new[] {
new { Value = "type1", Text = "product type 1" },
new { Value = "type2", Text = "product type 2" },
new { Value = "type3", Text = "product type 3" },
new { Value = "type4", Text = "product type 4" },
},
"Value",
"Text"
);
// pass the view model to the view
return View(model);
}
and finally inside your strongly typed view:
<%= Html.DropDownListFor(
x => x.SelectedProductType,
Model.ProductTypes,
"defaultValue"
) %>
I am looking for detailed ASP.NET MVC examples which make extensive use of grouped checkboxes (where multiple checkboxes can be selected, use case: choose the magazines you want to subscribe to with options such as "SI", "Forbes", "Money" etc) as well as grouped radio buttons (use case: at a bank choose either "savings" or "checking" account).
I have searched and found only scattered UI snipped but no complete MVC example which makes heavy use of these two UI elements and goes into detail on how the values from these elements are processed in the controller, captured in the model and persisted in the database.
Thanks,
The example here is for HTMLHelper for Checkbox Grouping
public static class HtmlHelperGroup
{
static string container = #"<div id=""{0}"">{1}</div>";
static string checkboxhtml = #"<input type=""checkbox"" name=""{0}"" value=""{1}"" {3} />{2}</br>";
public static string CheckBoxGroup(this HtmlHelper obj, string name, List<SelectListItem> data)
{
StringBuilder sb = new StringBuilder();
foreach (var content in data)
{
sb.Append(string.Format(checkboxhtml, name, content.Value,content.Text, content.Selected ? "checked" : string.Empty ));
}
return string.Format(container, "container_" + name, sb.ToString());
}
}
<%=Html.CheckBoxGroup("account", new List<SelectListItem>()
{
new SelectListItem() { Text="Checking", Value = "1" },
new SelectListItem() { Text="Saving", Value = "2" }}) %>
Hope this helps