Using Ajax to update ViewBag data ASP.NET MVC4 - asp.net-mvc-4

I'm currently have 2 class call City and District (1 to many relationship, respectively) .In my view I have 2 dropdown list, one for all the cities and the other for the districts (populated by using ViewBag). When a city is selected, I want the dropdown list for district to display only districts of that city without reloading the whole view. I had used Ajax before but only to re-populate data for model and not ViewBag. So how can I do it using Ajax and ViewBag ?

you can't repopulate the ViewBag itself.
I don't know if this is the best way but I would have done it the following way:
HTML:
<div>
<select id="city">
options
</select>
</div>
<div id="district-select">
<select>
</select>
</div>
JS:
$("#city").change(function() {
var id = $(this).val();
$.ajax({
type: "GET",
url:"/CONTROLLER/GetDistrictsByCity",
data: {cityId: id},
success: function(data) {
$("#district-select").html(data);
}
});
});
ACTION:
public ActionResult GetDistrictsByCity(Guid cityId){
//GET Districts that is linked to the cityId
return PartialView("_DistrictsByCity", model);
}
and then in the view "_DistrictsByCity" all you create is the dropdownlist. that html will then be taken and placed inside the div with the id "district-select"
Let me know if anything is unclear

it's bad idea to use ViewBag instead of StronglyTyped (Model)
so declare a ViewModel First and then pass your data to View via ViewModel

Related

Vue.js: binding select boxes, but don't want to ajax all the options

Good day. I'm using Vue.js to render an arbitrary number of select elements from the data in a component.
Here's sample JSON data that indicates there are two select elements, each with one or more options.
{
"dropdowns":[
{
"cd":"UG9ydGZvbGlv",
"formname":"sp_filter_UG9ydGZvbGlv",
"nm":"Portfolio",
"selected":"1a",
"options":[
{
"cd":"1a",
"val":"Option 1A"
}
]
},
{
"cd":"UHJvZHVjdCBOYW1l",
"formname":"sp_filter_UHJvZHVjdCBOYW1l",
"nm":"Product Name",
"selected":"2b",
"options":[
{
"cd":"2a",
"val":"Option 2A"
},
{
"cd":"2b",
"val":"Option 2B"
}
]
}
]
}
Here's the template HTML:
<form>
<div v-for="dropdown in dropdowns">
<div v-if="dropdown.availableToView">
<h4>{{dropdown.nm}}</h4>
<select v-model="dropdown.selected" v-on:change="triggerUpdate">
<option value="">(Make a selection)</option>
<option v-for="option in dropdown.options" :value="option.cd">{{option.val}}</option>
</select>
</div>
</div>
</form>
So far so good.
I've got the data loading and Vue is building the dropdowns.
When the user changes any select box (remember there can be an arbitrary number of them), the trigger action needs to submit ALL of the elements in the form via ajax. It sounds like the most correct option is to bind the form fields to the underlying component data, as I've done.
My triggerUpdate looks like this:
methods: {
triggerUpdate: function() {
axios({
method: "post",
url: actionURL,
data: this.dropdowns
})
.then(response => (this.data = response));
}
}
...but this submits the entire dropdowns data element, including all of the options in each select box. It's unnecessary to send all of the options in. I just want to send each field name along with its selected option (i.e. the "value").
I know i could serialize the whole form and make that my ajax payload. But that seems to be making an "end run" around Vue.js. Everyone talks about having your form fields bound to the Vue model...is it then correct to basically ignore the model when making an ajax request whose purpose is to then update the model?
I'm relatively new to Vue.js so I'd appreciate help with what I'm overlooking here. How should I go about sending in the data from the form (a) while using proper Vue.js binding and (b) without sending extraneous data?
Thanks for your time.
If you need to post only the selected values, and you store those in each dropdown's selected property, the sensible approach seems to be just mapping it to a simple array of name/value objects.
Try this (it assumes the name of each field is the formname property, if it isn't you can just replace it):
var submitData = this.dropdowns.map((dropdown) => {
return { name: dropdown.formname, value: dropdown.selected };
});
Then you send submitData in your ajax request.

Binding Gridview with drop down list selection MVC 5

I have a drop down list (Cities) and on selection it should be able to bind a Grid View in MVC 5
i am able to bind the drop down list and grid view but unable to handle the select event of Drop Down list. I dont know how to proceed on this I dont want to use Jquery. Below is my code
// BELOW IS THE DROP DOWN LIST CODE
#using (Html.BeginForm("BindGridView", "FacebookConfig", FormMethod.Post, new { id = "Id" }))
{
#Html.DropDownList("Cities")
}
// ON SELECTION OF ABOVE I SHOULD BE ABLE TO BIND THE BELOW GRID VIEW
#if (Model != null)
{
foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item.Keywords)
#Html.ActionLink("Edit", "Edit", new { id = item.Id })
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
// BELOW IS THE CODE IN CONTROLLER
public ActionResult Index()
{
var cities = So.BL.City.GetCities();
ViewBag.Cities = new SelectList(cities, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult BindGridView(int id)
{
var filter = So.BL.FacebookFilter.SelectFBApprovalFilters(id);
return View(filter);
}
If you want to perform an operation on dropdown on change event you must go for javascript/jquery for handling the element events. To satisfy your requirement you may do as,
Create a <div> to hold the new grid view to be created with the id to select.
Create a partial view that generate the grid view.
Create a function either in jquery/javascript for dropdown list on change event.
From the function call an action method using ajax.
Create an action method which would do what ever the functionality you want to do and return the partial view with the model required for generating the grid view.
Finally on success method of ajax call, write the output response to the inner html of the <div>.
If definitely not going for jquery or javascript then do a post back and from the selected dropdown value in the post method fetch the data for grid view and bind it to the grid. Note here the form submission will not occur on dropdown selection must use a submit button. Also show the grid based Model if not null.
Choose which one you likely to adopt.

using modal for each item in a list in yii framework

There is a list of patient data using a "TbGridView" widget,
Now, I want to use modal widget for each one of the patient here, so, that
the patient id is passed to the modal for each patient with patient id.
I had tried this, but, I am being unable to pass each patient id to the modal form.
Any response related to this would be very helpful.
Thank you.
Actually there is no direct way of doing that I mean that you cant render dynamic data by passing an id. Modal is static.
You can use ajax call for that to retrieve data from database and render that data in your modal. Follow these steps
1. In your gridview use rowHtmlOptionsExpression to set id for specific row.
2. create an action in your controller to handle ajax call.
3. use jquery click event on TbGridView elements like
$('#mygrid table tbody tr td:not(:first-child)').on('click', function() {
var Url =<?php echo '"' . CController::createUrl('/user/default/viewMessageAjax') . '"'; ?>;
var id = $(this).parent().attr('id');
console.log($(this));
$.ajax({
url: Url,
data: {id: id},
success: function(data) {
$('.modal-body').html(data);
$('#myModal').modal('show');
}
});
})
jQuery('#mygrid >table>tbody>tr:first-child').live('click', function() {
return false;
})
above code is just an example, you can change it according to ur needs.

Is it possible to model bind with a foreach loop in asp.net MVC4?

While researching this question I have found a reliable way to bind a list property.
See examples here:
https://stackoverflow.com/a/14157016/3229947
https://stackoverflow.com/a/6585642/1099260
Unfortunately, iterating through a list doesn't give me all of the functionality I need.
This code sample performs well for a Get
#foreach (Period period in Model.PeriodList)
{
<div> #Html.TextBoxFor(u => period.PeriodStartNumber) </div>
<div> #Html.TextBoxFor(u => period.PeriodEndNumber) </div>
}
But the values in these controls won't bind on a Post and and I'm left unable to update my model.
Is this a limitation of the framework and thus impossible?
#foreach (Period period in Model.PeriodList)
{
<div> #Html.TextBoxFor(u => period.PeriodStartNumber) </div>
<div> #Html.TextBoxFor(u => period.PeriodEndNumber) </div>
}
What happens here is , Suppose your PeriodList had 3 values and loop is executed 3 times, Now coming to the #Html.TextBoxFor(u => period.PeriodStartNumber) part this creates a text box with the NAME PeriodStartNumber or sometimes period.PeriodStartNumber for MVC to bind values to your model the html element tag name must match to your model field (and you also have 3 textboxes with the same name -> this is not good if you want to bind values induvidually). SO now I recon you dont have a field in your model with name PeriodStartNumber But you have PeriodList ie. there is no element with name PeriodList in the DOM to get binded with your model property so MVC will not bind it.
Just keep a parameter in controller post action like
public ActionResult SomeAction(Model myModel, string[] PeriodStartNumber )
{
}
you will have the values binded to PeriodStratNumber.
Note: Important thing to know while playing with MVC. Always make sure the Html element tag name and the model field name are the same. Only then binding will be done by MVC

ASP.NET MVC 4 form post to url

Only just started using MVC 4 & I am not sure how to do the following.
I have a page that displays a list of blog articles '/blog', this page also contains a select list with a list of dates, selecting a date should auto post the form to a URL like '/blog/date/20-05-2015' this URL routes to a ActionResult in a controller, which returns a list of blog articles from that date.
I dont know how to get my form to automatically post to a URL like '/blog/date/20-05-2015'
ROUTE:
routes.MapRoute(
"blogsByDates",
"blog/date/{date}",
new { controller = "Blog", action = "IndexByDate" }
);
CONTROLLER
public ActionResult IndexByDate(DateTime date)
{
var query = from c in db.Blogs
where c.PublishDate >= date
select c;
return View("Index", query.ToList());
}
VIEW (PARTIAL)
#using (Html.BeginForm())
{
<select name="ddlMonth" id="ddlMonth">
<option value="01-06-2012">June 2012</option>
<option value="01-05-2012">May 2012</option>
</select>
}
You'll have to use jQuery or something to change the ACTION attribute of your form. There's no other way to change the destination a form posts to. Though why you're using a form when you're not sending any special data to the server. Just make it a list of clickable links.