MVC3 strange hidden value missing during PartialView Ajax Call - asp.net-mvc-3

I'm having a very strange issue when rendering a partial view. My page has a table whose rows are rendered using a partial view. Here's a snippet
<td>
<img src="#Url.Content("~/Content/Images/edit_icon.gif")" class="editLine" />
<img src="#Url.Content("~/Content/Images/delete_icon.gif")" class="deleteLine" />
#Html.HiddenFor(model => model.LineId)
</td>
This renders fine when the page first loads. The input tags have the value set to the id. However, when I do an ajax call and return the PartialView from the controller, this value is always 0.
Controller code:
line.LineId = 12; //whatever the actual value is
return PartialView("Line", line);
And the jquery code is
$.ajax({
data: {
Id: id
},
success: function (data, textStatus) {
$('#lines').append(data);
}
When I debug through and look I see data has come back as
<input name="lineId" id="lineId" value="0" />
I debugged through EVERYTHING and the lineId is not 0. I then debugged throuh the view itself and whenever I did Html.Hidden("lineId", anyvalueHere) it rendered as 0. When I changed it to be Html.Hidden("lineId_" + actualId, actualId) it worked.
Is this known/expected behavior? I can imagine it not jiving with duplicate id's. However, it renders just fine on the page load where I use the exact same partial view. Is there magical juju for client side stuff? I would imagine not since it's just a controller action and it doesn't know the difference. Has anyone seen this. Thanks

If you are changing the value when you post, that is the issue. Use:
<input type='hidden' name='LineId' value='<%: Model.LineId %>'/>
instead of the Html.HiddenFor.

Related

Webgrid not displaying data MVC

I am trying to display model data in webgrid. I see that #grid has two rows in it, but nothing is displayed. Unable to figure out what is causing this to happen even though there is data in #grid.
I am trying to display one column just to test, but I also tried displaying all columns using #grid.GetHtml(), still nothing is shown in the UI. Any pointers is appreciated!
#model IEnumerable<MyProject.Domain.Entities.Tests>
#{
WebGrid grid = new WebGrid(Model);
}
<table>
<tr>
<td>
#if (Model.Count() > 0)
{
#grid.GetHtml(
columns:grid.Columns(
grid.Column(columnName:"Capacity",header:"Capacity")
))
}
else
{
<div>Please select slots and right click on context menu to view attributes.</div>
}
</td>
</tr>
</table>
I resolved this issue. I was putting the ajax datatype as json and I was returning partialview result. I changed the datatype in ajax post request to html. I also added a new function setData(data) and loaded the div with the html returned by ajax request. Hope this helps someone who might be doing the same mistake as me.
$.ajax({
type: "POST",
url: "/Home/ViewAttributes1",
data: postData,
success: function (data) {
SetData(data);
},
**dataType: "html",** (changed from json to html)
traditional: true
});
**added this function in which I am loading the div with the data returned by ajax**
function SetData(data)
{
$("#viewAttribs").html(data); // HTML DOM replace
}

MVC form post not reaching controller

I have a form that on submit doesn't reach the controller method (I put a breakpoint there)
[HttpPost]
public ActionResult SaveBilling( FormCollection fc )
{
...
}
the frontend code is something like this
<form action="/PersonSettings/SaveBilling" method="post" >
...
<input type='submit' value="save" />
</form>
any ideas ?
not sure if it is a route handler problem because it does reach the GET version if i go to /PersonSettings/SaveBilling in browser but the post method just yields a blank page and doesnt go into the code
Rewrite your view as:
#using (Html.BeginForm("SaveBilling", "PersonSettings", FormMethod.Post))
{
....
<input type='submit' value="save" />
}
Is this controller in any area or not?
I realize this has been solved, but I thought I'd tack on another possible cause: Having the [ValidateAntiForgeryToken] attribute on your method without an #Html.AntiForgeryToken() in your code will create the same problem.
Turns out it was a routing related issue after all , I have some complex routes and the default mvc route was catching things that should have gone through the default mvc route with areas.
Was able to recreate the issue by having explicit parameters for my function instead of a formcollection, so that might have been the issue ohwell.
use form and define action path.
<form id="subscriptionForm" action="/Category/Create" method="post">
--your div
</form >
Now use script to serialize the form
<script type="text/javascript">
$('#Save').click(function () {
var form = $("#subscriptionForm");
var url = form.attr("action");
var formData = form.serialize();
$.post(url, formData, function (data) {
$("#msg").html(data);
});
})
</script>
Now you can reach your controller action.
Sometimes using a network sniffing tool like Fiddler is helpful to see what's wrong when the request is sent and it seems not reaching the server.

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

MVC3 Ajax.BeginForm with PartialView and persistent routedata issue

I have a main view and the URL for this view has a Action/Controller/Area and id value, something like:
http://localhost:56513/Incident/IncidentHome/Index/8c02a647-a883-4d69-91be-7ac5f7b28ab7
I have a partialview in this main view, one that calls methods in the controller via Ajax. This partial view needs to know the ID value of the url for the parent page. I found how to do this is through 'ParentActionViewContent'. Something like:
using (Ajax.BeginForm("UpdatePersonalStatusPanel", "Status", new { area = "Tools" , id = ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() }, new AjaxOptions { UpdateTargetId = "divPersStatus" }))
{
<p style="text-align: center;">
<span class="editor-label">#Html.LabelFor(m => m.StatusText)</span> <span class="editor-field">#Html.EditorFor(m => m.StatusText)</span>
<input type="submit" value="Change Current Status" />
</p>
}
Now, this works fantastic for calling the controller method. The ID is passed correctly so that the controller can then see it in the routedata. I use the id to perform a database call, and then return the partialview again. The problem is on the return. I get a 'Object reference not set to an instance of an object' on the ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() bit in the ajax.beginform , and my targetid doesn't refresh.
Clearly I must be doing something wrong. Does someone else have a better way to see the parent view's routedata through Ajax?
If I'm understanding you correctly, this partial view calls itself. So ParentActionViewContext works the first time because the first time your main view calls an action using this partial view. However, later an ajax call directly returns this partial view. When the partial view is invoked directly there is no Parent View action hence the null reference on ParentActionViewContext.
Rather than deal with with route data I recommend including the id in the model of your partial view.
new { area = "Tools" , id = Model.Id }

MVC 3 Razor #Html.ValidationMessageFor not working in partial loaded via jquery.load()

I have put together a small example here just to replicate the problem.
I have a strongly typed partial view _Name.cshtml:
#model ValidationInPartial.ViewModels.MyViewModel
<h2>#ViewBag.Message</h2>
<fieldset>
<legend>Name</legend>
<div class="editor-label">
#Html.LabelFor(model => model.MyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MyName)
#Html.ValidationMessageFor(model => model.MyName)
</div>
Reload Name
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<script type="text/javascript">
$(document).ready(function () {
$("#reload").click(function () {
$("#divName").load("Home/NameReload");
});
});
</script>
that is initially loaded and displayed inside the main Index.cshtml
<div id="divForm">
#using (Html.BeginForm()) {
<div id="divName">
#Html.Partial("_Name")
</div>
}
</div>
The field MyName is required and validation is implemented through Required attribute in MyViewModel
namespace ValidationInPartial.ViewModels
{
public class MyViewModel
{
[Required(ErrorMessage = "Please enter a Name.")]
public string MyName { get; set; }
}
}
After the page is loaded the first time, if you click the Create button leaving the field empty the validation message "Please enter a Name." shows beside the field and the field itself turns pink, which is the expected behaviour.
Now by clicking the "Reload Name" link, which makes an ajax call (jquery.load(...)), the partial is reloaded, here is controller code:
public PartialViewResult NameReload()
{
MyViewModel myViewModel = new MyViewModel();
ViewBag.Message = "Name Reloaded";
return PartialView("_Name", myViewModel);
}
This time if you click the Create button leaving the field empty the validation message does not appear beside the field, although the field turns pink.
It turns out that when reloading the partial the #Html.ValidationMessageFor doesn't render the validation message as the first time.
Here is the jquery files I use
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
I wonder if this is a bug in the way the Razor engine renders the #Html.ValidationMessageFor or is that a problem with jquery?
Any idea why this happens?
I have also read somewhere that the ajax call looses all the scripts for the page, in fact I have to keep any javascript code inside the partial so that they can be rendered and used again.
In the meantime I found a workaround which is to manually render in the partial what was supposed to be rendered by #Html.ValidationMessageFor which is:
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="MyName"></span>
However this workaround means that if we change the type of validation or just the validation message inside the Required attribute in the ViewModel, we need to modify this hard-coded piece of html in the view.
#NickBork has a great answer here. The key is that ASP.NET's MVC rendering engine does not output the validation script if it doesn't think that there is a form. The example given hacks it buy putting in a form and then selection an inner section of HTML from was was returned, essentially throwing the outer wrapper of the form away.
There is another method so that you can just get your view:
ViewContext.FormContext = new FormContext();
With this method, there won't actually be FORM code output, but the validation markup will be there.
Thanks,
John
Validation markup (span tags, custom field attributes, etc) are not rendered unless your fields are contained within a FORM. The validation plugin itself does not work with elements outside of a form.
When ASP.NET renders your Partial View the controls are not within a form and thus do not get the elements rendered.
When you load you're partial content you'll need to parse the HTML using a jQuery selector.
In my sample below I have a TBODY on the parent View page that contains rows. When I need to add additional rows, I make a call to a View which had a form, table, tbody and collection of rows.
$.ajax({
type: "POST",
url: "/controller/action",
data: ({Your: 'dataHere'}),
dataType: "html",
success:
function(response){
$('tbody').append($('tbody',$(response)).html());
//The validation plugin can't bind to the same form twice.
//We need to remove existing validators
$('form').removeData("validator");
//Refresh the validators
$.validator.unobtrusive.parse(document);
},
error:
function(){
alert('An error occured while attempting to add the new content');
}
});
Note that I'm using a jQuery selector to select the rows that are inside of the View/PartialView that are loaded in by using AJAX:
$('tbody',$(response)).html()
The rest of the wrapper just appends the rows from the AJAX View/PartialView to the calling parents tbody:
$('tbody').append($('tbody',$(response)).html());
A couple other notes, after the validator plugin has been run on a form, it can not be called again without re-adding it (see jquery.validate.unobtrusive not working with dynamic injected elements)
To fix this, I first call the following method to remove all validators:
$('form').removeData("validator");
$("form").removeData("unobtrusiveValidation");
I then refresh the validators using the following:
$.validator.unobtrusive.parse(document);
I can't remember where I found the solution. The reason is because you are loading a PartialView into a View that has already been parsed by the jquery.validator.unobtrusive library. You need to re-parse the unobtrusive library
function ReparseValidation(){
jQuery.validator.unobtrusive.parse("#yourcontainer");
}

Resources