How return Partial from Action getJSON - getjson

I'm having a problem with method using $.getJSON. It's very simple and it looks like that:
Take ID из DropDownlList CategoryId
<div id="partial" class="editor-label">
#* #Html.Partial("");*#
</div>
$(document).ready(function () {
$('#CategoryId').change(function () {
$.getJSON('/Publication/AjaxAction/' + this.value, {},
function (html) {
$("#partial").html(html);
alert("go");
});
});
});
send in
public ActionResult AjaxAction(int Id)
{
if (Request.IsAjaxRequest())
{
if (Id== 1)
{
ViewBag.SourceTypeId = new SelectList(db.SourceTypes, "Id", "Title");
ViewBag.CityId = new SelectList(db.Cities, "Id", "Title");
return Partial("_CreateStatya");
}
}
return PartialView();
}
Could you please tell me how to return Partial in ??
<div id="partial" class="editor-label">
#* #Html.Partial("");*#
</div>

$(document).ready(function ()
{ $('#CategoryId').change(function ()
{ $.get('#Url.Action("AjaxAction","Publication")',
{id:$('#CategoryId').val()}, function (html)
{ $("#partial").html(html);
alert("go"); },'html');
}); });

Related

Why IdentityRole id gets overriden by old name in View

I'm trying to make an Edit Form for IdentityRole. When the page is loaded I normaly receive the model with Id something like this "09e43076-c333-4145-bccb-8bc7f9db470e", but when the view is created I see that #Html.HiddenFor(m => m.Id) gets an old name value instead of Id (see screenshots in the links below). Why is it happening? Thanks!
GET: Edit
[HttpGet]
public ActionResult Edit(string id)
{
_context = new ApplicationDbContext();
if (User.Identity.IsAuthenticated)
{
if (!isAdminUser())
{
return RedirectToAction("Login", "Account");
}
}
else
{
return RedirectToAction("Login", "Account");
}
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var role = roleManager.FindByName(id);
return View(role);
}
View: Edit
#model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
#{
ViewBag.Title = "Edit Role";
}
<h2>Edit User Role:</h2>
#section RolesCSS {
<link href="#Url.Content("~/Views/Role/style/style.css")" rel="stylesheet"/>
<div class="form-group">
#using (Html.BeginForm("Edit", "Role", FormMethod.Post, new { #class = "AddRoleForm" }))
{
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.Users)
<div class="Label">
<p>Edit New User Role Name:</p>
</div>
<div class="FormControl">
#Html.EditorFor(m => m.Name, new {htmlAttributes = new {#class = "form-control"}})
</div>
<div class="FormControl">
<input class="btn btn-default" type="submit" value="Edit Role"/>
</div>
}
</div>
}
screenshot of values received as model in the view
screenshot of the source of the rendered html
Despite I've found a solution I'm still interested what was wrong with the first aproach.
I've found a workaround here (the content/explanation is in russian lang)
I created a class EditRoleModel as a temporary model, to avoid the issue I was having before,
public class EditRoleModel
{
public string Id { get; set; }
public string Name { get; set; }
}
that I pass as a model to View:
[HttpGet]
public ActionResult Edit(string id)
{
_context = new ApplicationDbContext();
if (User.Identity.IsAuthenticated)
{
if (!isAdminUser())
{
return RedirectToAction("Login", "Account");
}
}
else
{
return RedirectToAction("Login", "Account");
}
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var role = roleManager.FindByName(id);
var model = new EditRoleModel() {Id = role.Id, Name = role.Name};
return View(model);
}
then I slightly change the View to recieve model of type EditRoleModel:
#model WebUI.Models.EditRoleModel
#{
ViewBag.Title = "Edit Role";
}
<h2>Edit User Role:</h2>
#section RolesCSS {
<link href="#Url.Content("~/Views/Role/style/style.css")" rel="stylesheet"/>
<div class="form-group">
#using (Html.BeginForm("Edit", "Role", FormMethod.Post, new { #class = "AddRoleForm" }))
{
<div>#Model.Id</div>
#Html.HiddenFor(m => m.Id)
<div class="Label">
<p>Edit New User Role Name:</p>
</div>
<div class="FormControl">
#Html.EditorFor(m => m.Name, new {htmlAttributes = new {#class = "form-control"}})
</div>
<div class="FormControl">
<input class="btn btn-default" type="submit" value="Edit Role"/>
</div>
}
</div>
}
and finaly this is the controller where I update the IdentityRole:
[HttpPost]
public ActionResult Edit(EditRoleModel model)
{
_context = new ApplicationDbContext();
if (User.Identity.IsAuthenticated)
{
if (!isAdminUser())
{
return RedirectToAction("Login", "Account");
}
}
else
{
return RedirectToAction("Login", "Account");
}
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
IdentityRole role = roleManager.FindByName(model.Id);
if (role != null)
{
role.Name= model.Name;
IdentityResult result = roleManager.Update(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Something went wrong!");
}
}
return View(model);
}

Kendo Ui Grid not rebinding after search button click

I having difficulty where the Kendo Ui grid would not rebind with new result after the Search button click.Please let me know how i could achieve this. Thank you
Currently the GetList will return data correctly however the KendoUi grid would not rebind with the new result.
.cshtml
<div id="search">
<div>
<div class="searchOption">
#Html.LabelFor(model => model.HRN)
#Html.EditorFor(model => model.HRN)
</div>
</div>
<div>
<div class="smallBox">
<input type="button" id="btnSearch" style="height:32px; font-size:14px; background-color:#3399FF" class="k-button" title="Search" value="Search" />
</div>
</div>
<div>
<div class="searchOption">
#Html.LabelFor(model => model.FamilyName)
#Html.EditorFor(model => model.FamilyName)
</div>
</div>
<div>
<div class="searchOption">
#Html.LabelFor(model => model.GivenName)
#Html.EditorFor(model => model.GivenName)
</div>
</div>
<div>
<div class="searchOption">
#Html.LabelFor(model => model.Priority)
#Html.EditorFor(model => model.Priority)
</div>
</div>
</div>
#(Html.Kendo().Grid<PWeb_App.ViewModels.ResultModel>()
.Name("Result")
.HtmlAttributes(new { #Style = "align:center; font-size:10px; width:985px" })
.Events(ev => ev.Change("onChange"))
.Columns(columns =>
{
columns.Bound(p => p.GivenName).Width(90);
columns.Bound(p => p.FamilyName).Width(90);
columns.Bound(p => p.Community).Width(130);
})
.ToolBar(toolbar => toolbar.Save())
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Sortable()
.Pageable(paging => paging
.Input(false)
.Numeric(true)
.PreviousNext(true)
.PageSizes(new int[] { 5, 10, 25, 50 })
.Refresh(false)
)
.Selectable()
.Scrollable()
.ColumnMenu(c => c.Columns(false))
.DataSource(dataSource => dataSource
.Ajax()//bind with Ajax instead server bind
.PageSize(10)
.ServerOperation(true)
.Model(model =>
{
model.Id(p => p.Pid);
model.Field(p => p.FamilyName).Editable(false);
model.Field(p => p.GivenName).Editable(false);
})
.Read(read => read.Action("GetData", "Details").Type(HttpVerbs.Get))
.Update("Edit", "Details")
)
)
<script type="text/javascript">
$(document).ready(function () {
$('#btnConsumerSearch').click(function (e){
var community = $("#Community").val();
var familyName = $("#FamilyName").val();
var givenName = $("#GivenName").val();
$.ajax({
type: 'POST',
complete: function(e) {
$("#Result").data("kendoGrid").dataSource.read();
},
url: "#(Url.Content("~/Details/GetData/"))",
data: {
"Community":community,
"FamilyName":familyName,
"GivenName":givenName
},
success: function () {
$("#btnSearch").removeAttr('disabled');
}
});
$("#btnSearch").attr('disabled','disabled');
});
});
</script>
controller:
//The following code will return data new result as expected however the kendo grid does not refresh with the result of the following code:
public ActionResult GetData([DataSourceRequest] DataSourceRequest request, SearchCriteria model)
{
DataTable result = GetList(model);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
/// <summary>
/// Get all available List from Client table and return using datatable
/// </summary>
/// <returns></returns>
private DataTable GetList(SearchCriteria model, string ReferralListID)
{
using (PEntities context = new PEntities())
{
string ConnectionString = (context.Connection as EntityConnection).StoreConnection.ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
builder.ConnectTimeout = 2500;
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlCommand cmd = new SqlCommand("spListResults", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("paramCommunity", SqlDbType.VarChar, 100).Value = !String.IsNullOrEmpty(model.Community) ? (object)model.Community : DBNull.Value;
cmd.Parameters.Add("paramGivenName", SqlDbType.VarChar, 100).Value = !String.IsNullOrEmpty(model.GivenName) ? (object)model.GivenName : DBNull.Value;
cmd.Parameters.Add("paramFamilyName", SqlDbType.VarChar, 100).Value = !String.IsNullOrEmpty(model.FamilyName) ? (object)model.FamilyName : DBNull.Value;
cmd.Parameters.Add("paramPriority", SqlDbType.VarChar, 10).Value = !String.IsNullOrEmpty(model.Priority) ? (object)model.Priority : DBNull.Value;
adapter.SelectCommand = cmd;
cmd.CommandTimeout = 0;
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}
}
}
Try like this,
In your grid read method in view like this
.Read(read => read.Action("GetData", "Details").Data("GetData"))
You button should be Submit Type
<input type="Submit" id="btnSearch" style="height:32px; font-size:14px; background-color:#3399FF" class="k-button" title="Search" value="Search" />
Script
function GetData() {
return {
HRN: $('#HRN').val(),
FamilyName: $('#FamilyName').val(),
GivenName: $('#GivenName').val(),
Priority: $('#Priority').val()
};
}
$(document).ready(function () {
$("#btnSearch").click(function (e) {
$("#Result").data("kendoGrid").dataSource.read();
$("#Result").data("kendoGrid").refresh();
e.preventDefault();
});
});
Controller
public ActionResult GetData([DataSourceRequest] DataSourceRequest request, string HRN, string FamilyName, string GivenName, string Priority)
{
DataTable result = GetList(HRN,FamilyName,GivenName,Priority);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

Fine Uploader in Form Doesn't Submit Model Data into Controller

I have 2 questions:
1.) I have placed the Fine Uploader in a form and now I'm wondering why I don't see the filled content of the entry fields in my controller. How I can solve that?
2.) How can I do field validations before the upload process fires?
I hope someone can help!
Here is my code:
Model:
public class UploadFileModel
{
[StringLength(100)]
[Display(Name = "* Title:")]
public string Title { get; set; }
[StringLength(300)]
[Display(Name = "Description:")]
public string Description { get; set; }
}
View:
#model mowee.Models.UploadFileModel
<link href="~/Scripts/fineuploader/fineuploader-3.5.0.css" rel="stylesheet" />
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { id = "uploadForm", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Video Upload</legend>
<ol>
<li>
#Html.LabelFor(m => m.Title)
#Html.TextBoxFor(m => m.Title, new { #Class = "action add", title = "Enter your video/movie title here." })
</li>
<li>
#Html.LabelFor(m => m.Description)
#Html.TextAreaFor(m => m.Description, new Dictionary<string, object> { { "rows", "3" } })
</li>
</ol>
<div id="bootstrapped-fine-uploader"></div>
<script src="~/Scripts/fineuploader/fineuploader-3.5.0.js"></script>
<script>
function createUploader() {
var uploader = new qq.FineUploader({
element: document.getElementById('bootstrapped-fine-uploader'),
multiple: false,
validation: {
sizeLimit: 2147483648 //2GB
},
request: {
endpoint: '/Home/UploadFile'
},
text: {
uploadButton: '<div><i class="icon-upload icon-white"></i>* Upload Video</div>'
},
template: '<div class="qq-uploader span12">' +
'<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
'<div id="btnUpload" class="qq-upload-button btn btn-success" style="width: 33%;">{uploadButtonText}</div>' +
'<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
'<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' +
'</div>',
classes: {
success: 'alert alert-success',
fail: 'alert alert-error',
dropActive: "cssClassToAddToDropZoneOnEnter"
}
});
}
window.onload = createUploader;
</script>
</fieldset>
}
Controller:
[HttpPost]
[AllowAnonymous]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult UploadFile(string qqfile, UploadFileModel myModel)
{
if (ModelState.IsValid)
{
try
{
HttpPostedFileBase uploadFile = null;
uploadFile = Request.Files[0];
if (uploadFile != null && uploadFile.ContentLength > 0)
{
if (myModel.Title != null || myModel.Description != null)
{
**//but UploadFileModel is null. WHY??????? Anyone an idea what i did wrong???
//write data to DB**
}
}
else
{
ModelState.AddModelError("", "Please choose a video/movie.");
return Json(new { success = false, message = "Please choose a video/movie." }, "application/json");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", "An error occured. Try again.");
mailUtils.SendBugMail(ex, this.HttpContext);
return Json(new { success = false, message = "An error occured during upload. Try again." }, "application/json");
}
return Json(new { success = true, VideoLink = #ViewBag.VideoLink, VideoTranscoded = #ViewBag.Transcoded }, "application/json");//"text/html");
}
return Json(new { success = false, message = "An error occured during upload. Try again." }, "application/json");
}
OK. I figured it out. The params can be set on callback 'onSubmit' with setParams like that:
callbacks: {
onSubmit: function (id, fileName, responseJSON) {
uploader.setParams({
idxTitle: $('#titleId').val(),
idxAuthor: $('#authorId').val(),
idxEmail: $('#emailId').val()
});
},
And it works fine!
Addressing your questions:
You should really have a look at the MVC4 example in the Fine Uploader server-side examples repository. Model your server-side code after this example, and you should be fine. I personally am not an MVC4 developer, but I know the example I have linked to works.
You can make use of onValidate and onValidateBatch callbacks to perform your own validation tasks. Please have a look at the callbacks documentation for more info.

dropdowns in asp.net mvc 2

I have asp.net mvc application in c# language. I want to develop the scenario like, my page will have have the 4 dropdown controls. on the selection of first , second's item should be load, on selction of 2'nd, 3'rd dropdown should be load it item. where as 4'th is independent. but on 4'th dropdown I want to change the UI design. what strategy I have to use here? how can i implement this scenario here.?
Edited:
Controller->action
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetSubjects(int standardId)
{
List<Subject> subjectList = basicEntityManager.GetSubjects(standardId);
JsonResult result=Json(subjectList, JsonRequestBehavior.AllowGet);
return result;
}
i am able to debug this but not fetching data.
Script:
<script type="text/javascript">
$(function() {
$('#StandardId').change
(function() {
var url='/Test/GetSubjects';
fetchItems(url, { standardId: $(this).val() }, $('#SubjectId')
);
/* $('#SubjectId').change(function() {
fetchItems(
'/Test/GetChapters',
{
selectedItem1: $('#SubjectId').val(),
selectedItem2: $(this).val()
},
$('#SelectedItem3')
);
});*/
});
});
function fetchItems(url, data, ddl) {
$.getJSON(url, data, function(items) {
alert(items);
$.each(items, function() {
ddl.append
(
$('<option/>').val(this.Value).text(this.Text)
);
});
});
}
function OnStandardChange() {
var standard = document.getElementById("StandardId");
var subject = document.getElementById("SubjectId");
var ActionUrl = "/Test/GetSubjects/"
alert("Hi");
// $.getJSON('/Test/GetSubjects', { standardId: standard.val() }, function(data) { });
}
$('#StandardId').change(function() {
});
function OnSubjectChange() {
}
function OnChapterChange() {
}
function addOption(selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
</script>
You could cascade with AJAX:
Model:
public class MyViewModel
{
public string SelectedItem1 { get; set; }
public IEnumerable<SelectListItem> Items1 { get; set; }
public string SelectedItem2 { get; set; }
public string SelectedItem3 { get; set; }
public string SelectedItem4 { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// Load initial data
Items1 = Enumerable.Range(1, 5).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
})
};
return View(model);
}
public ActionResult Items2(string selectedItem1)
{
// invoked to populate the second DDL
return Json(
Enumerable.Range(1, 3).Select(x => new { Value = x, Text = x }),
JsonRequestBehavior.AllowGet
);
}
public ActionResult Items3(string selectedItem1, string selectedItem2)
{
// invoked to populate the third DDL
return Json(
Enumerable.Range(1, 3).Select(x => new { Value = x, Text = x }),
JsonRequestBehavior.AllowGet
);
}
public ActionResult Items4(string selectedItem1, string selectedItem2, string selectedItem3)
{
// invoked to populate the fourth DDL
return Json(
Enumerable.Range(1, 3).Select(x => new { Value = x, Text = x }),
JsonRequestBehavior.AllowGet
);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
<script type="text/javascript">
$(function () {
$('#SelectedItem1').change(function () {
fetchItems(
'<%= Url.Action("items2") %>',
{
selectedItem1: $(this).val()
},
$('#SelectedItem2')
);
});
$('#SelectedItem2').change(function () {
fetchItems(
'<%= Url.Action("items3") %>',
{
selectedItem1: $('#SelectedItem1').val(),
selectedItem2: $(this).val()
},
$('#SelectedItem3')
);
});
$('#SelectedItem3').change(function () {
fetchItems(
'<%= Url.Action("items4") %>',
{
selectedItem1: $('#SelectedItem1').val(),
selectedItem2: $('#SelectedItem2').val(),
selectedItem3: $(this).val()
},
$('#SelectedItem4')
);
});
$('#SelectedItem4').change(function () {
alert('changing UI');
});
});
function fetchItems(url, data, ddl) {
$.getJSON(url, data, function (items) {
$.each(items, function () {
ddl.append(
$('<option/>').val(this.Value).text(this.Text)
);
});
});
}
</script>
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedItem1, new SelectList(Model.Items1, "Value", "Text"))
<%= Html.DropDownListFor(x => x.SelectedItem2, Enumerable.Empty<SelectListItem>()) %>
<%= Html.DropDownListFor(x => x.SelectedItem3, Enumerable.Empty<SelectListItem>()) %>
<%= Html.DropDownListFor(x => x.SelectedItem4, Enumerable.Empty<SelectListItem>()) %>
<input type="submit" value="OK" />
<% } %>

.each() not working in IE

I want to get all labels inside a div, the blow piece of code works in Firefox and not working IE. Any idea. Thanks in advance.
<div id='discounts'>
<label id="discount1"> discount 1</label>
<label id="discount2"> discount 2 </label>
<input type="text" id="discountmisc" value="" />
</div>
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
selectLabels.getLabels();
Are you wrapped in DOM Ready functions? i.e.
$(function () {
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
selectLabels.getLabels();
});
or alternately:
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
$(selectLabels.getLabels);
or finally (because you don't care about the return value):
var selectLabels = {
getLabels: function() {
$(function () {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
});
}
};
selectLabels.getLabels();
Tell me, and if so, I'll change my answer.