Ext.Net MVC - Render partial view with parameter - asp.net-mvc

I have a partial view on my mvc page. The view is rendered by default with no data, but will be updated based on a value selection from a combobox in another section of the page. The partial view takes an id as a parameter which it will use to get the data needed to return the model.
The problem that I am having is that on the initial load, the parameter is null since nothing has been selected and I am getting a null value exception.
Is there a way that I can use an if statement in a direct events call to check the selected item and return 0 is that is null?
See me sample code below for clarification.
Thanks
Here are the relevant parts of my main page (index.cshtml) -
x.ComboBox()
.ID("MyCombo")
.DisplayField("Title")
.ValueField("Number")
.TypeAhead(false)
.Width(500)
.PageSize(10)
.HideBaseTrigger(true)
.MinChars(0)
.TriggerAction(TriggerAction.Query)
.DirectEvents(de =>
{
de.Select.Url = Url.Action("MyPartial");
#* Can I use an if statment here to check the selected item's value? *#
de.Select.ExtraParams.Add(new { id = App.MyCombo.getValue() });
})
.ListConfig(Html.X().BoundList()
.LoadingText("Searching...")
.ItemTpl(Html.X().XTemplate()
.Html(#<text>
<div class="search-item">
<h3><span>{Number}</span>{Title}</h3>
{Description}
</div>
</text>)
)
)
........
#Html.Partial("MyPartial", Model.MyPartialVM)
and here is my controller code -
public ActionResult MyPartial(string id)
{
var vm = new MyPartialViewModel
{
Number = id,
Title = "New Title"
};
ViewData.Model = vm;
var pvr = new Ext.Net.MVC.PartialViewResult
{
ViewData = this.ViewData
};
return pvr;
}
This works if I hardcode a parameter value, but not if I try it as it is now. Here is the error I get -
Message=Cannot perform runtime binding on a null reference
So I was thinking that I can do an if in teh DirectEvents piece to check for a null on the combobox selection, I can inject a 0 when necessary and handle that in the controller. Can this be done?

Try if this works:
x.ComboBox()
.ID("MyCombo")
.DisplayField("Title")
.ValueField("Number")
.TypeAhead(false)
.Width(500)
.PageSize(10)
.HideBaseTrigger(true)
.MinChars(0)
.TriggerAction(TriggerAction.Query)
.DirectEvents(de =>
{
de.Select.Url = Url.Action("MyPartial");
de.Select.ExtraParams.Add(new {
Name = "id",
Value ="App.MyCombo.getValue() == null ? '0' : App.MyCombo.getValue()",
Mode = ParameterMode.Raw
});
})
.ListConfig(Html.X().BoundList()
.LoadingText("Searching...")
.ItemTpl(Html.X().XTemplate()
.Html(#<text>
<div class="search-item">
<h3><span>{Number}</span>{Title}</h3>
{Description}
</div>
</text>)
)
)

Related

To reduce code duplication in controller

This is my simple controller which is dependent on EventsViewModel. After fetching required fields, i am comparing the data returned and fill it into two variable and finally returning back UpcomingPassedEventViewModel to the view page.
public ActionResult Event()
{
int currentUserId = this.User.Identity.GetUserId<int>();
var events = this.db.Events
.Where(e => e.AuthorId == currentUserId)
.OrderBy(e => e.StartDateTime)
.Select(e => new EventsViewModel()
{
Title = e.Title,
StartDateTime = e.StartDateTime,
Name = e.ApplicationUser.UserName
});
var upcomingEvents = events.Where(e => e.StartDateTime > DateTime.Now);
var passedEvents = events.Where(e => e.StartDateTime <= DateTime.Now);
return View(new UpcomingPassedEventViewModel()
{
UpcomingEvents = upcomingEvents,
PassedEvents = passedEvents
});
}
Now, i have a partial view _Events like this:
#model App.Models.UpcomingPassedEventViewModel
<div class="row">
#if (Model.UpcomingEvents.Any()) {
#Html.DisplayFor(x => x.UpcomingEvents) }
else {
<div class="col-md-4 col-sm-6 col-xs-12">No events</div> }
</div>
I can render this partial view on Events view page corresponding to events action method in Event controller like this:
#{ Html.RenderPartial("_Events"); }
If i try to render it anywhere else it will throw System.NullReferenceException: Object reference not set to an instance of an object. error on this line ---#if (Model.UpcomingEvents.Any())
Problem is:
1>If i want to render same partial view on home controller's index view then i have to write full code in index method also.
2> If i do that, then code duplication problem. suppose i have 10 controller and corresponding views then i will have to write same code over and over again.
How to reduce this code duplication. i am already using view model. how to resolve this. I dont want to use repository pattern here.

asp.net mvc fill a dropdownlist according to the item selected in an author

i'm a total beginner in asp.net mvc and am trying to change the items in a dropdownlist according to the item selected in an author one (they are filled from a database)
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "TheForm" }))
{
Filiere: <%= Html.DropDownList("filiere", (SelectList)ViewData["filiere"], new { onchange = "this.form.submit();" })%>
Module:<%= Html.DropDownList("module",(SelectList)ViewData["module"])
}
%>
public ActionResult Index(int? fil)
{
var fi = db.filiere.Select(f => new {f.id,f.nom });
ViewData["filiere"] = new SelectList(fi.AsEnumerable(), "id", "nom");
List<module> mod;
if (fil == null)
mod = db.module.ToList();
else
{
mod = (from module in db.module
where module.id_filiere == fil
select module).ToList();
}
ViewData["module"] = new SelectList(mod.AsEnumerable(),"id","nom");
return View();
}
Try to create one more method in controller who accept the author information and return the list which you want to display in drop-down.
then simply put ajax call on author change event call the controller method for data and also pass current author information and on success bind result what you get from controller method to drop-down.

Returning a value from controller to partial view using 'return PartialView(..)

I am working on a project that requires me to achieve the following:
Make a selection from a drop down menu in a partial view
Pass the id of the selected value to the action method in my controller
Use that id to query the db to get a new value
Return and display that value in a text box on the same partial view
For example, if I choose a different fund then the fund code for that fund will display in the text box.
Here is the relevent code in my partial view. What I'm trying to do here is either get a value from the model if it exists or get the default value from the query.
protected void Page_Load(object sender, EventArgs e)
{
var qry = (from id in _db.myTable
select new
{
id.Code,
}).FirstOrDefault();
_changedId = Model.Code ?? qry.Code;
}
<td><%: Html.DropDownListFor(fn1 => Model.Id, _val, new { #id = myId" } )%>
</td>
<td class="labels">
Value:
</td>
<td>
<%= Html.TextBoxFor(fc => Model.Value, new { #Value= _changedId, #readonly = true }) %>
</td>
NOTE: I'm aware that this is not best practice for MVC but this is how the project was written.
Here is the action method:
public ActionResult GetFundCode(MyModel fnc)
{
int fid = fnc.Id;
var qry = (from tab in _db.AnotherTable
where tab.Id == fid
select tab).FirstOrDefault();
fnc.newCode = qry.Code;
return PartialView("~/Views/TransactionCommonInputs/FromToFundSearchSelector.ascx",fnc);
}
My action method does 'work' in that it return the correct value in the model 'fnc'. I get the new value and assign this in a page load section of the partial view posted above and again here:
_changedId = Model.fundCode ?? qryFundCode.FundCode;
Running through VS2010 debugger shows that the value returned from the controller to my partial view is correct. That is when I hover over '_changedValue' it is assigned the value that I want:
<%= Html.TextBoxFor(fc => Model.Value, new { #Value= _changedId, #readonly = true }) %>
</td>
However, the value displayed when I run the code reverts to a previous value.
I hope this is more understandable than my first post.

send kendoGrid parameters(filters, sort) for file download

I am trying to send my filters from a grid in order to export an excel file with the filters applied. I am new to kendo, and I am having difficulties sending the filters,page,sorting to the controller. Here is what i have so far :
Controller
public JsonResult List([DataSourceRequest] DataSourceRequest request)
{
//generating list to send to the grid
return Json(list.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
View
Html.Kendo().Grid(Model)
.Name("tokenList")
.Columns(columns =>
{
// columns for the model
})
.DataSource(d => d.Ajax()
.ServerOperation(true)
.Read(read => { read.Action("List", "Settings", null); })
)
.ToolBar(toolbar =>
{
toolbar.Template(
#<text>
EXPORT
</text>
);
})
.DefaultSetupForApp(<-this adds filtering, sortable, pageable).
Render();
}
And this is my JS function for getting parameters(I saw this piece of code somewhere else, and I am trying to adapt it, here is where i think i need help)
function onDataBound(e) {
var grid = this;
// ask the parameterMap to create the request object for you
**I need some info on this part, nothing i found was very helpful**
var requestObject = (new kendo.data.transports["aspnetmvc-server"]({ prefix: "" }))
.options.parameterMap({
page: grid.dataSource.page(),
sort: grid.dataSource.sort(),
filter: grid.dataSource.filter()
});
// Get the export link as jQuery object
var $exportLink = grid.element.find('.export');
// Get its 'href' attribute - the URL where it would navigate to
var href = $exportLink.attr('href');
// Update the 'page' parameter with the grid's current page
href = href.replace(/page=([^&]*)/, 'page=' + requestObject.page || '~');
// Update the 'sort' parameter with the grid's current sort descriptor
href = href.replace(/sort=([^&]*)/, 'sort=' + requestObject.sort || '~');
// Update the 'pageSize' parameter with the grid's current pageSize
href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + grid.dataSource.total());
//update filter descriptor with the filters applied
href = href.replace(/filter=([^&]*)/, 'filter=' + (requestObject.filter || '~'));
// Update the 'href' attribute
$exportLink.attr('href', href);
}
I just want to send the filters to the controller. Can you help me ?
I managed to do it. All i had to do was give the var grid to correct grid, like this :
var grid= $('#tokensList').data('kendoGrid');
I do this way :
Here my grid toolbar template.
<a class="k-button" id="export" href="Equipment/Export?page=~&pageSize=~&filter=~&sort=~" title="Export to Excel">
<span class="k-print" />
</a>
Let me know in case of any problem.

How to assign value to dropdown for viewbag element?

I am developing MCV app with Razor syntax.
I have pass the elements to the dropdown list and I want to show selected item in that dropdown from viewbag element.
below code displays the dropdow code.
Controller Code
[SessionFilterAction]
public ViewResult Details(int id)
{
ViewBag.HODList = new SelectList(db.Employees.Where(e => e.DesignationType == "HOD"), "Id", "FullName");
ViewBag.ItemToBeSelectedInList = 5;
return View(paymentadvice);
}
View Code
if(ViewBag.DesignationTypeOfLoggedUser == "Staff")
{
#Html.DropDownList("HODList", String.Empty ,new { ???? })
}
Now I want to use viewbag element which will be select the one of the item of dropdown.
How to do this ?
ViewBag is designed to pass data from the controller to the view not to the other way.
You can use HTTP Get method for populating drop down like
[HttpGet]
public MyAction()
{
MyModel model = new MyModel();
// model.DropDwonValues is generic list class in model
model.DropDwonValues= db.Values //replace with your db table
.Select(v => new DropDownItem
{
Text = v.Name //value to go in your text field
Value = v.Id.ToString() //value to go in your ID field
})
.ToList();
return View(model);
}
Then in your view you can do:
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.DropDownId)
#Html.DropDownListFor(m => m.DropDownId , Model.DropDwonValues )
}

Resources