how to pass Model with Url.Action? - asp.net-mvc

I want to return a partial view in Jquery Dailog and wanted to pass the viewmodel object to particular controller action, how to do that?
View
#Html.DropDownListFor(model => model.SelectedCountry, new SelectList(Model.CountryList, "CountryCode", "CountryName"), "---SELECT COUNTRY---",
new { #class = "chosen", #onchange = "this.form.action='/Home/Index'; this.form.submit(); " })
<input type="button" id="button1" value="Push"/>
<div id="dialog" title="Report" style="overflow: hidden;"></div>
Js
<script type="text/javascript">
$(function () {
$('#dialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Report',
modal: true,
open: function() {
//here how to pass viewmodel
$(this).load("#Url.Action("CreatePartial")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$('#button1').click(function () {
$('#dialog').dialog('open');
});
});
Controller
public ActionResult CreatePartial(HomeViewModel homeViewModel)
{
return PartialView("_CreatePartial", homeViewModel);
}
Currently, "homeViewModel.SelectedCountry" is Null, how to pass model in Jquery?

If you're using AJAX, you should not use HTTP GET to pass model to server. Instead use HTTP POST (as in $().ajax({method: 'POST'}) and pass data as POST data ($().ajax({method: 'POST', data: #Html.Raw(Json.Encode(Model))}))

You convert the model into an JSON object by using the the build-in JSON-helper, just modify your request to:
$(this).load('#Url.Action("CreatePartial")',#Html.Raw(Json.Encode(Model)));
#Html.Raw is needed to prevent HTML-Encoding.
I tested it and it worked.

Related

ASP.NET MVC 5: Client Validation is not working for a view model (annotations) [duplicate]

I have JQuery popups and i want to put required field validations on it and for this i have set required attributes in model and have also set the validation message for them in the view but that required field validations are not working on popups. Required field validation is working fine on forms other than JQuery Popups....Please guide me that what should i do to tackle this issue...Following is my code.
Model
[Display(Name = "Material Code")]
[Required(ErrorMessage = "*")]
public string MaterialCode { get; set; }
View
<li>
#Html.LabelFor(m => m.MaterialCode)
#Html.TextBoxFor(m => m.MaterialCode)
#Html.HiddenFor(m => m.MaterialCodeId)
</li>
and following is my cod eto open a JQuery popup.
$('#btnAddCharge').on('click', function (event) {
event.preventDefault();
var actionURL = '#Url.Action("Edit", "Charges", new { Id = 0, #ticketId = #TicketId, UserId = UserId })';
$(dialogBox).dialog({
autoOpen: false,
resizable: false,
title: 'Edit',
modal: true,
show: "blind",
width: 'auto',
hide: "blind",
open: function (event, ui) {
$(this).load(actionURL, function (html) {
$('form', html).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (res) {
if (res.success) {
$(dialogBox).dialog('close');
}
}
});
return false;
});
});
}
});
$(dialogBox).dialog('open');
});
The validator is parsed when the page is initially loaded. When you add dynamic content you need to reparse the validator. Modify your script to include the following lines after the content is loaded
$(this).load(actionURL, function (html) {
// Reparse the validator
var form = $('form');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
$('form', html).submit(function () {
....
Side note: The code you have shown does not include #Html.ValidationMessageFor(m => m.MaterialCode) but I assume this is included.

Render a partial view inside a Jquery modal popup on top of a parent view

I am rendering a partial view on top of the parent view as follows on a button click:
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("AddUserAction", "UserController")');
}
});
});
When user click AddUser button i am giving a jquery modal pop up with partial view rendered in it. But when user click save on partial view I am saving the entered information into database. But i have to show the pop up again on the parent view to add another user, until they click on cancel. Please help me how to load the partial view on top of the parent view.
Thanks
I suggest you create a jquery ajax function to post form data, then use the call back function to clear the form data. This way unless the user clicks the cancel button, the dialog is always showing.
See below example:
Main View
<button class="AddUser">Add User</button>
<div id="AddUserForm"></div>
Partial View (AddUserPartialView)
#model Demo.Models.AddUserViewModel
<form id="myForm">
<div id="AddUserForm">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
</div>
</form>
Js file
$('.AddUser').on('click', function () {
$("#AddUserForm").dialog({
autoOpen: true,
position: { my: "center", at: "top+350", of: window },
width: 1000,
resizable: false,
title: 'Add User Form',
modal: true,
open: function () {
$(this).load('#Url.Action("AddUserPartialView", "Home")');
},
buttons: {
"Add User": function () {
addUserInfo();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
return false;
});
function addUserInfo() {
$.ajax({
url: '#Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function(data) {
if (data) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
}
});
}
Action
public PartialViewResult AddUserPartialView()
{
return PartialView("AddUserPartialView", new AddUserViewModel());
}
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = true;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
}
return Json(isSuccess);
}
Update
If you want to show the error message when errors occurred while saving the data, you could change the Json result in AddUserInfo action like below:
[HttpPost]
public JsonResult AddUserInfo(AddUserViewModel model)
{
bool isSuccess = false;
if (ModelState.IsValid)
{
//isSuccess = Save data here return boolean
}
return Json(new { result = isSuccess, responseText = "Something wrong!" });
}
then add a div element in your partial view:
#model MyParatialView.Controllers.HomeController.AddUserViewModel
<div id="showErrorMessage"></div>
<form id="myForm">
<div id="AddUserForm">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name)
</div>
</form>
finally, the addUserInfo JS function should be like :
function addUserInfo() {
$.ajax({
url: '#Url.Action("AddUserInfo", "Home")',
type: 'POST',
data: $("#myForm").serialize(),
success: function (data) {
if (data.result) {
$(':input', '#myForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
} else {
$("#showErrorMessage").append(data.responseText);
}
}
});
}

DropDownListFor automatic postback

How would I implement something like automatic postback for DropDownListFor in MVC. Currently, after selecting a value in dropdown I have to refresh the page to see the changes applied to the page.
In View,
The dropdownlistfor is like
#Html.DropDownListFor(m => m.SelectedItem, Model.MyItemList, new { #id = "DropDownListForId"})
and the onchange event is handled as such
<script type = "text/javascript">
$(function () {
$('#DropDownListForId').change(function () {
var item = $(this).val();
$.ajax({
url: '#Url.Action("SomeAction", "SomeController")',
type: 'GET',
data: { value: item },
success: function(result) {
}
});
});
});
</script>
Thanks!
I think you can simply achieve this by submitting form on change event of DropDownList
Assuming myForm as you form id
<script type = "text/javascript">
$(function () {
$('#DropDownListForId').change(function () {
$('form#myForm').submit();
});
});
</script>

Issue when submitting form data via JQuery UI Dialog to the server

I have an asp.net mvc app, using JQuery UI dialog. I'm trying to submit form data to the controler action method. I do hit the action method but my object has no data. Do you know why?
From Filter.cshtml
$("#selectUnits").dialog({
autoOpen: false,
title: 'Select Units',
width: 400,
modal: true,
minHeight: 200,
buttons: {
"Cancel": function () {
$(this).dialog("close");
},
"Submit": function () {
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").submit(), function (data) {
alert('This worked');
});
}
} // END OF BUTTONS
}); //END OF DIALOG
From Controler...Action Method:
public void SetUnitNumbers(object data)
{
int a = 5;
}
From SelectUnits.cshtml where form 'frmSelectedUnits' lives. Essentially it is a bunch of checkboxes values that I'm trying to send back to the server:
<body>
<form id="frmSelectedUnits" action="/" >
<div id="unitNumberCheckboxes" style=" ">
<div>
#Html.CheckBox("SelectAllUnitNumbers", false)<label for="SelectAllUnitNumbers"><b>Select/Unselect All Units</b></label>
</div>
<div id="unitCheckboxes">
#foreach (var item in Model)
{
<div style="float:left">
#Html.CheckBox("UnitNumbers", false)<label for="UnitNumbers">#item.unit_number.ToString().PadLeft(3, '0') </label>
</div>
}
</div>
</div>
</form>
</body>
jQuery .post is:
$.post(url, data, success-callback-function);
where data is A map or string that is sent to the server with the request.
Calling $("#frmSelectedUnits").submit() probably won't work.
Try:
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").serialize(), function (data) {
alert('This worked');
});
jQuery docs on .serialize()

How to generate a pop up page link in ASP.NET MVC

How to generate a javascript link in asp.net mvc?
eg.
Pop it
Can I use Html.ActionLink and how to do this?
I could do something like this:
Pop it
But I just want to find out will there be some better solutions for this?
Many thanks.
Yes, you can do something like:
<%=Html.ActionLink(model.Title, "View", "PoppedView", new { Id = model.Id.ToString() }, new { target="_blank" })%>
I would look at doing this using jQuery UI and a dialog instead of a new window. You can use the open handler to load up the content into the dialog.
<%= Html.ActionLink( "Pop It",
"ItemDetail",
"Item",
new { ID = model.ID },
new { #class = "popup-link" } ) %>
<script type="text/javascript">
$(function() {
$('.popup-link').click( function() {
var href = $(this).attr('href');
$('<div><p class="popup-content"></p></div>').dialog({
autoOpen: true,
modal: true,
height: 200,
width: 400,
open: function() {
$(this).find('.popup-content').load(href);
},
close: function() {
$(this).dialog('destroy');
}
});
return false;
});
});
</script>

Resources