How to return result to a partial view with kendo grid and kendo textboxes - kendo-ui

I'm having a problem in returning values to my view for kendo grid & fields.
Earlier I had only kendo grid in my partial view and hence I used below code to return the values of my grid:
public virtual ActionResult GetValues(long Id1, [DataSourceRequest]DataSourceRequest request)
{
return Json(ViewModel.List<Another_View_Model>.ToDataSourceResult(request));
}
My View Model structure is as follows
ViewModel
{
public long Id { get; set; }
public List<Another_View_Model> Another_View_Model { get; set; }
}
But now, I'm adding kendo textboxes, checkboxes to the same partial view and would like to return server values to those fields too while returning grid values.
My View Model structure is as follows
ViewModel
{
public long Id { get; set; }
public List<Another_View_Model> Another_View_Model { get; set; }
public string textboxField { get; set; }
}
In my controller, I'm doing the following changes but my textbox field values are not returning to the view.
public virtual PartialViewResult GetValues(long Id1)
{
return PartialView("_PartialView", ViewModel);
}
Can anyone please point me where I'm doing wrong or is there a better wayto return result for both grid & kendo elements at the same time within the same model.
My view structure is as follows:
#model ViewModel
#(Html.Kendo().TextBoxFor(p => p.textboxField)
.Name("TextBox")
)
#(Html.Kendo().Grid<Another_View_Model>()
.Name("KendoGrid")
Any help with this is appreciated. Thanks in advance!!

Use either TextBoxFor(p => p.PropertyName) or TextBox().Name("PropertyName") DO NOT use both. The name property will override the TextBoxFor. So in your example, your Kendo Textbox is actually binding to a Property named TextBox instead of textboxField like you were expecting.
The inverse is also true, if you were posting a form, the Model's textboxField will be null, while if you had a string parameter named TextBox it will be populated with the textbox's value

Related

Binding dynamic data to kendo Dropdownlist

I am trying to bind a kendo dropdownlist with the model but I am getting undefined in each option.
Model:
public SelectList CountriesTemp { get; set; }
public int Country{get;set;}
Controller:
public ActionResult Registration()
{
RegistrationModel Model = new RegistrationModel();
Model.CountriesTemp = new SelectList(ObjService.GetCountries(), "CountryID", "Country_Name");
return View(Model);
}
View Page
#(Html.Kendo().DropDownListFor(m => m.Country)
//The name of the dropdownlist is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("Country_Name") //Specifies which property of the Product to be used by the dropdownlist as a text.
.DataValueField("CountryID") //Specifies which property of the Product to be used by the dropdownlist as a value.
.BindTo(Model.CountriesTemp ) //Pass the list of Products to the dropdownlist.
)
Can somebody please guide me where I am wrong because if I bind a simple dropdownlist of MVC , It works well. Just one line change as below in ViewPage and it's Working.
#Html.Dropdownlist("CountriesTemp")
It looks like you've got a conflict (so-to-speak going on here). Try something like this:
#(Html.Kendo().DropDownListFor(m => m.Country)
.DataTextField("Text")
.DataValueField("Value") // These may be optional now
.BindTo(Model.CountriesTemp))
Alternatively, you can not use a SelectList and do a property like IEnumerable<Country> Countries { get; set; } on your Model. Then the binding would look something like:
#(Html.Kendo().DropDownListFor(m => m.Country)
.DataTextField("Country_Name")
.DataValueField("CountryID")
.BindTo(Model.Countries))

How to select multiple items from dropdown list, save it and again repopulate the dropdown with the selected list?

I am working on an ASP.NET MVC3 project. I am facing issues regarding multiple selection in dropdown.
The problem is, I have to save multiple items in database from a dropdown list and repopulate it.
I have used the class below to represent each list data:
public class IDNameValueTO {
public int ID { get; set; } //Value of the selection Element
public string Name { get; set; } //Name of the selectionElement
public int Value { get; set; } //1 if value is checked and 0 if not
}
My List goes as follows:
public List<IDNameValueTO> tempList = new List<IDNameValueTO>();
ViewBag.SelectedList = tempList;
I am generating the dropdown list as follows:
#Html.DropDownList("SelectedValue", new SelectList(ViewBag.SelectedList, "ID", "Name"))
Now how do I save the multiple selection and display it later on using dropdown?
The default DropDown helper that is provide in asp.net mvc does not support multiselet.
You'll have to create your own custom multiselect dropdown helper.
Here are some links that can help you create you own custom dropdown helper:
http://blogs.msdn.com/b/rickandy/archive/2012/01/30/asp-net-mvc-dropdownlist-multiselect-and-jquery.aspx
http://utsavized.com/chosen-multiselect-dropdown-list-with-asp-net-mvc3/

Required field not present on all pages leading to problems

I have a ‘Create’ page in my MVC3 application that has 4 input fields that are all required. I also have an ‘Edit’ page in which 3 of these 4 fields can be edited. I do not want to display the 4th field and want to maintain it at its initial value (the field is the date that the entry was created ).
I mark the 4th field as [Required] in the model then this causes the model to be declared as invalid in post action method of the Edit field. If I omit the [Required] annotation then someone can create a user with a null value for this 4th field.
How can I get around this problem?
Model Code:
[Required]
[DisplayName("User Name")]
public string UserName { get; set; }
[Required]
public string Role { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayName("Insert Date")]
public DateTime? InsertDate { get; set; }
[Required]
[DisplayName("Active")]
public bool ActiveInd { get; set; }
Controller Code:
public ActionResult Edit(int id, ZUserRoleModel mod)
{
if (ModelState.IsValid)
{
// code removed
return RedirectToAction("Index");
}
return View(mod);
}
You can make that field as hidden in edit mode.
#Html.HiddenFor(x => x.EntryDate)
Not sure if you still need an answer for this, but what you need to do in order for the
#Html.HiddenFor(x => x.EntryDate )
to work, is pass an existing model into view. So let's assume that your action for getting the user data looks like this. ( You did not supply it, so I am not sure if this is right )
Public ActionResult GetUser(int UserID)
{
ZUserRoleModel model = new ZUserRoleModel(UserID);
// Maybe this could go to your database and gather user
// It would populate the correct data into a model object
return View("Edit", model);
}
With combination of the hidden field, your view will be populated with the existing user information, and the hidden field will be populated with data, and it will be passed to your edit action.
NOTE: I wrote this without any kind of testing, but it should still work, or at the very least, I hope it points you in the right direction if you still need assistance.
You can use fluentvalidation: http://fluentvalidation.codeplex.com/
Have a rule that's something like
RuleFor(user => user.field4).NotEmpty().When(ViewContext.Controller.ValueProvider.GetValue("action").RawValue <> "edit")

Binding DropdownList and maintain after postback

I am using MVC3. I'm binding the dropdown with the Data coming from a service. But after the page posts back and a filter applies to list, the dropdown shows the filter record value in the grid because I always bind the list coming from the service.
However, I want the dropdown to always show all the Records in the database.
I don't understand your question that clearly. But it seems that it is a dropdown that you have on your view? I also have no idea what you are trying to bind so I created my own, but have a look at my code and modify it to fit in with your scenario.
In your view:
#model YourProject.ViewModels.YourViewModel
On the view there is a list of banks in a dropdown list.
Your banks dropdown:
<td><b>Bank:</b></td>
<td>
#Html.DropDownListFor(
x => x.BankId,
new SelectList(Model.Banks, "Id", "Name", Model.BankId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.BankId)
</td>
Your view model that will be returned to the view:
public class YourViewModel
{
// Partial class
public int BankId { get; set; }
public IEnumerable<Bank> Banks { get; set; }
}
Your create action method:
public ActionResult Create()
{
YourViewModel viewModel = new YourViewModel
{
// Get all the banks from the database
Banks = bankService.FindAll().Where(x => x.IsActive)
}
// Return the view model to the view
// Always use a view model for your data
return View(viewModel);
}
[HttpPost]
public ActionResult Create(YourViewModel viewModel)
{
if (!ModelState.IsValid)
{
// If there is an error, rebind the dropdown.
// The item that was selected will still be there.
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
return View(viewModel);
}
// If you browse the values of viewModel you will see that BankId will have the
// value (unique identifier of bank) already set. Now that you have this value
// you can do with it whatever you like.
}
Your bank class:
public class Bank
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
This is simple as it gets. I hope this helps :)
PS: Please remember with future posts, always give as much detail as possible so that we can help you better. Also don't forget to display code samples so that we can see what you have already done. The more details that we can have the better.
When you post the model back to the create[Http Post] action is it not possible to have the list of dropdown list values for the banks binded back to the model. I see that if the model is invalid, you call the code
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
to get a list of all the banks again which I assume you need to hit the database again.
Thanks

asp.net mvc3 updated (refresh) the viewmodel in view

I send a BOOKVIEWMODEL with fields and a simple IEnumerable in view I get the this list IEnumerable in the view by a method with JSON AJAX in view and I fill my table Ristourne(View) with JQUERY it works very well but I not know how I fill (BIND or refresh) the list IEnumerable of my BOOKVIEWMODEL in the VIEW to recovered it in the Controller:
[HttpPost]
public ActionResult Create(BookViewModel _bookViewModel)
{
if (ModelState.IsValid)
{
_bookViewModel.Ristourne
return RedirectToAction("Index");
}
return View(_bookViewModel);
my bookviewmodel
public class BookViewModel
{
public String book { get; set; }
public String price { get; set; }
public IEnumerable<Ristourne> Ristourne { get; set; }
}
For the model binding to work, you need to "mimic" the convention MVC uses when generating the form fields.
I don't know the contents of the Ristourne class, but let's say it had 1 field called Foo.
In that case, when you render out the elements (from the JSON AJAX callback), make them look like this:
<input type="text" name="Model.Ristourne[0].Foo" id="Model.Ristourne[0].Foo"/>
<input type="text" name="Model.Ristourne[1].Foo" id="Model.Ristourne[1].Foo"/>
<input type="text" name="Model.Ristourne[2].Foo" id="Model.Ristourne[2].Foo"/>
And so on. Easiest thing to do is in your AJAX callback, just use a basic for loop to create the elements indexer.
Altenatively, a cheat/easy way around this problem would be to make your AJAX action return a PartialViewResult:
public PartialViewResult Book()
{
var ristournes = _repo.Get();
var model = new BooksViewModel { Ristourne = ristournes };
return PartialView(model);
}
Then the partial view:
#Html.EditorFor(model => mode.Ristourne)
Then MVC will create the form fields correctly.
I always prefer this option over dynamically generated form fields. If you want to go down this path often, you should consider something like Knockout.js and/or Upshot.

Resources