MVC3 Razor conditional loading - asp.net-mvc-3

I want to implement following:
A combobox/DropDownListFor named "target" in a view. It contains (e.g.) A and B as choice.
In the same view I have another combobox named "medium". Its content depends on the chosen target, e.g.:
- if target = "A", combobox "medium" will show 1 and 2 as choice.
- if target = "B", combobox "medium" will show 3 and 4 as choice.
I have implemented combobox "target" successfully, but I don't know how to implement combobox "medium" related to "target". If I am not wrong, the logic should be: get the chosen targetid -> find all medium related to the targetid -> fill combobox "medium" with the result.
Here is snippet of my current view (combobox "target"):
<div class="editor-label">
#Html.LabelFor(model => model.TargetId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.TargetId, (ViewData["targets"] as SelectList).MakeSelection(Model.TargetId))
</div>
Thx in advance.

You could use the javascript OnChange of the first drop to do an ajax call to obtain the values based from the choice A or B.
Then with the JSon response you get from the controller you fill the dropdown "Medium"
in the JS file do something like this:
$(document).ready(function () {
$("#target").change(function () { GetMediumValues("#target", "#medium"); });
});
function ClearDrop(objSource) {
$(objSource).empty();
}
function GetMediumValues(objSource, objDest) {
var url = '/mySite/GetMediumValues/';
$.getJSON(url, { id: $(objSource).val() }, function (data) {
ClearDrop(objDest);
$.each(data, function (index, optionData) {
$(objDest).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
}
While in the controller
public ActionResult GetMediumValues(string id)
{
int myId = 0;
int.TryParse(id, out myId);
var select = new SelectList(repository.GetMediumValues(myId), "Id", "Name");
return Json(select, JsonRequestBehavior.AllowGet); //allow get needed to allow get calls
}

Related

on check box check send value to partial view and update it mvc 3

i have two partial view one is having a 5 checkbox (for filtering) and another will display the filtered data.
<input type="checkbox" data-toggle="checkbox" id="2000-5000"/>Rs.2000-Rs.5000
<input type="checkbox" data-toggle="checkbox" id="2000-5000"/>Rs.2000-Rs.5000
and with help of jquery am sending the request to controller..
public PartialViewResult PhonesPartail(int? id,string where)
{
var list = paginateRsult(id, "", where).ToList();
ViewData["totalpages"] = totalPages;
return PartialView("_phonelist",list);
}
and the jquery
$(document).on("change", ".price-checkbox input[type=checkbox]", function () {
if ($(this).is(":checked")) {
var prange = $(this).attr("id");
var parray = prange.split('-');
var whereclause = "price>=" + parray[0] + " and price <=" + parray[1];
$.ajax({
url: '../../Phones/PhonesPartail',
data: { where: whereclause },
type: 'POST',
success: function (data) {
$("#phone-list").append(data);
}
});
}
});
now the list which is returned , is getting added to the div with entire html page.. means again the html page is getting added in the div..
any solution..
Thanks in advance...
use html() function of jquery
It will paste data returned by partial view in to a div rather then appending it to div
$("#phone-list").html(data);

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?
My main page has a DropDownList (DropDownListFor) and a partial view which ONLY contains a list of "items". The items shown in this partial view are dependent upon the item selected in the DropDownList. There's a 1 to many relationship between the DropDownList item and the items in the partial view. So, when the user changes the value of the DropDownList, the content in the partial view will dynamically change to reflect the item selected in the DropDownList.
Here's my DropDownList:
<div data-role="fieldcontain">
Choose Capsule:<br />
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules" })
<br />
</div>
Here's my Partial View declaration on the same page:
<div data-role="fieldcontain">
#Html.Partial("_FillerPartial", Model.Fillers)
</div>
I'm not very familiar with Ajax, but looking at other examples, here's what I have for my Ajax:
$(document).ready(function () {
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
alert("server returned: " + data);
}
});
});
});
And finally, here's a screenshot of what's going on. By changing the "Choose Capsule" drop down list, I want the Filler list to update dynamically:
You can load the drop down list as a partial view from the controller using ajax.
The controller code:
[HttpGet]
public virtual ActionResult GetFillersByCapsule(string cappk)
{
var model = //Method to get capsules by pk, this returns a ViewModel that is used to render the filtered list.
return PartialView("PartialViewName", model);
}
The main view html:
<div id="filteredList">
</div >
The partial view
#model IEnumerable<MyCapsuleModel>
foreach (var x in Model)
{
//Render the appropriate filtered list html.
}
And you can load the filtered list using ajax:
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
$("#filteredList").empty();
$("#filteredList").html(data);
}
});
});
Hope this helps.
You can't update the partial, per se, because the partial will never be rendered again without a page reload. Once you receive the HTML, ASP is done, you're on your own at that point.
What you can do, of course, is switch out the content of a particular div or whatever using JavaScript. Your example in particular screams Knockout, so that's what I would recommend using.
Change your HTML to add a data-bind to your containing div:
<div data-role="fieldcontain" data-bind="foreach: filler">
<button data-bind="text: name"></button>
</div>
And your DropDownList:
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules", data_bind = "event: { change: updateFillers }" })
Then, some JavaScript:
var FillersViewModel = function () {
var self = this;
self.fillers = ko.observableArray([]);
self.updateFillers = function () {
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
self.fillers(data.fillers) // where `fillers` is an array
}
});
}
}
var viewModel = new FillersViewModel();
ko.applyBindings(viewModel);
This is a very simplistic example, and you'll need to do some more work to make it do everything you need it to do in your scenario, but the general idea is that every time the dropdown list is changed, Knockout will call your updateFillers method, which will execute the AJAX and put new data into the fillers observable array. Knockout automatically tracks changes to this array (hence the "observable" part), so an update is automatically triggered to any part of your page that relies on it. In this scenario, that's your div containing the buttons. The foreach binding will repeat the HTML inside for each member of the array. I've used a simple button element here just to illustrate, but you would include the full HTML required to create your particular button like interface. The text binding will drop the content of name in between the opening and closing tag. Refer to: http://knockoutjs.com/documentation/introduction.html for all the binding options you have.
There's much more you could do with this. You could implement templates instead of hard-coding your HTML to be repeated in the foreach. And, you can use your partial view to control the HTML for this template. The important part is that Knockout takes the pain out of generating all this repeating HTML for you, which is why I recommend using it.
Hope that's enough to get you started.

MVC3 Text Box Text change Event

I have the following scenario, using mvc3:
I have a database table which holds a RecordID, RecordName and RecordType. Displayed are three text boxes, one for each of the fields mentioned previously.
My Question is, when i enter a RecordID into the relevant text box, i want to be able to show the RecordName and RecordType for that particular RecordID. How can i achieve this?
In View:
#Html.TextBoxFor(model => model.RecordId)
#Html.TextBoxFor(model => model.RecordName)
#Html.TextBoxFor(model => model.RecordType)
<script language="javascript">
$('#RecordId').change(function(){
var recordId = this.value;
$.getJSON("/MyController/GetRecordById",
{
id: recordId
},
function (data) {
$('RecordName').val(data.Name);
$('RecordType').val(data.Type);
});
});
</script>
In Controller:
public JsonResult GetRecordById(int id)
{
var record = recordRepository.GetById(id);
var result = new {
Name = record.Name,
Type = record.Type
}
return Json(result, JsonRequestBehavior.AllowGet);
}

Set div id dyanmically in each item in the loop to be referred in Ajax.ActionLink method?

Do we have better ways to handle it?
#foreach (var item in Model)
{
<div id="divDetail#{#item.CategoryId}"/>
#Ajax.ActionLink(
item.CategoryName,
"GetDetails",
new { id = item.CategoryId },
new AjaxOptions() { UpdateTargetId = string.Format("divDetail{0}", item.CategoryId) })
}
</div>
}
I would use the HTML.ActionLink helper method to generate the link and then use my custom jQuery ajax call to get the data. The advantage of doing this is i have full control so that i can do some manipulation of the response data before showing in the detail div.
I added a CSS class to the link so that i can be more specific (in selection of element) when binding my functionality.
#foreach (var item in Model)
{
<div id='divDetail#(item.ID)'></div>
#Html.ActionLink(item.CategoryName, "GetDetails", new { #id = item.CategoryId}, new {#id= "link-"+item.CategoryId, #class="lnkItem" })
}
and the script is
<script type="text/javascript">
$(function () {
$(".lnkItem").click(function (e) {
e.preventDefault();
var itemId = $(this).attr("id").split("-")[1]
$.get($(this).attr("href"), { id: itemId }, function (data) {
//i am free to do anything here before showing the data !
$("#divDetail" + itemId).html(data);
})
});
});
</script>

Passing strongly type form model data in asp.net mvc through jquery

It is easy to submit form to an action method in the controller which has strongly typed textboxes for example, with a submit button, but what if I want to send the exact same form with the strongly typed textboxes through jquery perhaps the $.ajax call after something else has been clicked.
code like this:
#Html.TextBoxFor(m => m.topTenFav.YoutubeLink,new { id="youTubeLinkTxt"})
does all the work for us and it's very simple to map the properties of our object in the controller
[HttpPost]
public ActionResult AddTopTenFav(HomeViewModel topTen)
{
topTen.topTenFav.Date = DateTime.Now;
topTen.topTenFav.UserName = User.Identity.Name;
repository.AddTopTen(topTen);
repository.Save();
return RedirectToAction("Index");
}
How would I send this form to the controller, map the textboxes in the form to object's properties on a click event such as
$("#btnAddGenre").click(function () {}
#using (Html.BeginForm(
"AddTopTenFav", "Home", FormMethod.Post, new { id = "AddTopTenFavForm" }))
{
<span id="youTubeLinkSpan">Youtube Link</span>
<div>
#Html.TextBoxFor(m => m.topTenFav.YoutubeLink,new { id="youTubeLinkTxt"})
</div>
<span id="youTubeNameSpan">Song Title</span>
<div>
#Html.TextBoxFor(m => m.topTenFav.Title,new { id="youTubeNameTxt"})
</div>
<button type="submit" name="btnSubmit" value="">submit</button>
}
You can do the following post:
$(document).ready(function(){
$('#btnAddGenre').click(function () {
$.post(
$('#AddTopTenFavForm').attr('action'),
$('#AddTopTenFavForm').serialize,
function (data) {
window.location = #Url.Action("Index");
},
'html' // returned data type
);
});
});
I use the html data type so you can return whatever you want and the redirect occurs on the window.location using the #Url.Action to give the location.
Please if it work mark as accepted answer
yes you can post the data of strongly typed textboxex using jquery.
First you have to do
take the values of all the textboxex in jquery using the below code.
var xx= $("#xx").val();
this will give the val in xx from your mvc text box.
Then by using jquery ajax call you can call the action method.
the code is below.
$.get("/XXXX/YY/1", { xxName: xx }, function (data) {
var status = data;
alert(status);
if (status) {
return true;
}
else {
alert("The book with this name is already present. TRY DIFFERENT NAME!")
return false;
}
});
here xxxx is controller amd yy is action method name.the next parameter is the value of all the textboxes which you want to send as an parameter.
This will perform the ajax call and return the value.
Please tell me if you find any problem the i will give the whole code.

Resources