How to create a partial view that posts - asp.net-mvc

i have created a partial view (a button that has icon) like this:
#model int
<a type="button" class="btn btn-primary btn-sm" href="#Url.Action("Edit", new {id = Model})">
<span class="glyphicon glyphicon-pencil"></span>
<span>Save</span>
</a>
but this one uses the GET not the POST. also, how can I get all of the value's that I typed from the textboxes as parameter to the partial view?

Try this:-You will use AJAX call for post method and return partial view like below.
[HttpPost]
public ActionResult ActionForAjaxForm(FormModel model)
{
// do something like save the posted model
return PartialView("_YourPartialView", model);
}

Try this way, It may help you.
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: "ClientCode=" + code/*{ "ClientCode": code }*/, //First item has latest ID
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
$('#dialog').html(data);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
In Controller
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ClientViewModel clientViewModel = this.Service.FindByClientCode(ClientCode);
if (clientViewModel == null)
{
return HttpNotFound();
}
return View("ShowClient", clientViewModel);
}
for more details please see Working example

Related

Pass value from anchor to controller

How can I pass the value of name.report to the controller withoout passing it through a URL, this is in a side bar. I'm sorry if this is a really simple question, but I have searched quite a lot and couldn't find a solution
#foreach (var name in Model.namesReport)
{
<li href="#" class=""><a class="menu_name"> #name.ReportName</a>
}
Controller
[HttpPost]
public ActionResult test(int? id)
{
return null;
}
Ajax call
$("getReport".click(function() {
$ajax({
url: '/Home/test',
type:'POST',
datatype: 'json',
data: {id:"test"}
});
});

method is called twice

What was I doing wrong?
My method is called twice.
First time I get Id and it's correct behavior
Second time I get Null
I can't get it what is correct way to solve it?
My View
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
<a class="btn btn-primary" data-index="#item.Id" name="link">Go to anywhere</a>
</div>
</div>
</div>
</div>
}
</div>
</div>
My Controller
[HttpGet]
public ActionResult ListCoach(int id)
{
if (id != null)
{
var ChoachList = _TraningService.Coach(id);
return View(ChoachList);
}
return HttpNotFound();
}
Script
I use script on My View use helper #Section {}
#section scripts {
#*<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>*#
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
type: "GET",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/TrainingType/ListCoach';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index");
alert("Clicked: " + valueOfClickedTag);
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index");
var callFunc = PassToContoller(valueOfClickedBtn)
});
});
</script>
}
if I use the method:
I can't get into View ListCoach
Can I return Json on My View?
[HttpGet]
public JsonResult ListCoach(int id)
{
var ChoachList = _TraningService.Coach(id);
return Json(ChoachList,JsonRequestBehavior.AllowGet);
}
Your code seems to be OK and in theory, your action should not call twice but I want to show you some ways in order to catch the problem:
when a call is made to the server in chrome developer tools in the tab network you will see a record in which there is a column named Initiator that shows you the call is created by who and where.
you can use keyword DEBUG in the first of function PassToContoller and look at the stack to know who one call your function
and about your final question, my answer is negative and you can not use this way to pass JSON object to your view but you can pass JSON object beside model by ViewBag or ViewData
In your function PassToContoller,in ajax success,you use window.location.href = '/TrainingType/ListCoach';,so after you call the function,it will have two requests,one with ajax,one with window.location.href.
If you want to get jsondata in ajax,you need to use dataType: "json", in ajax.
Here is a demo to pass json data:
Action:
[HttpGet]
public JsonResult GetJson(int id)
{
return new JsonResult(new TestModel { Id=id,Name="Test"});
}
View:
<button onclick="test()">
test
</button>
#section scripts
{
<script>
function test() {
$.ajax({
type: "GET",
url: 'GetJson',
data: { id: 1 },
dataType: "json",
success: function (data) {
console.log(data);
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
</script>
}
result:
Update:
You can try to use a form to pass Id to action(without using <a></a>):
<form asp-action="GetJson" asp-route-id="#item.Id">
<input type="submit" value="Go to anywhere" />
</form>
Action:
[HttpGet]
public IActionResult GetJson(int id)
{
return View("Index",new List<TestModel> { new TestModel { Id = id, Name = "Test" } });
}

Unable to pass Id from listbox items in mvc 5

I've coded for multiple values that resides inside listbox on button click. I have used autocomplete textbox to get the required value along with its id. Then i managed to add those values inside the listbox. Now what i want is to pass id's against those values in listbox instead of names. Below is my code that I'm running.
StudentBatch.cs
public string studentId { get; set; }
public string StudentName { get; set; }
public List<string> selectedids { get; set; }
public List<string> names { get; set; }
public List<string> SelectedNames { get; set; }
Create.cshtml
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
<input type="button" value="Add Text" id="addtypevalue" />
<div id="typevaluelist"></div>
</div>
</div>
<div id="new" style="display:none;">
<div class="typevalue">
<input type="text" name="typevalue" />
<button type="button" class="delete">Delete</button>
</div>
</div>
<div id="hiddensq">
</div>
for (int i = 0; i < Model.names.Count; i++)
{
#Html.Hidden("UserValues", Model.names[i]);
}
#Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.names))
<div id="partialDiv">
#{
Html.RenderPartial("GetListBox", Model);
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/CreateStudent",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.FirstName, id: item.Id };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
<script>
$(function () {
$('#addtypevalue').click(function (e) {
var name = $("#StudentName").val();
alert(name);
$('#SelectedNames').
append($("<option></option>").
attr("value", name).
text(name));
$('#hiddensq').append("<input name='UserValues' type='hidden' value='"+ name +"'/>");
});
});
</script>
StudentController.cs
public ActionResult Create()
{
Context.Student student = new Context.Student();
Models.StudentBatch studBatch = new Models.StudentBatch();
studBatch.names = new List<string>();
studBatch.names.Add("Add Student Names");
studBatch.BatchNumberList = student.getBatchList();
return View(studBatch);
}
[HttpPost]
public JsonResult CreateStudent(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "f14570f0-e7a1-4c22-bf69-60ffbeb7e432";
var StudentList1 = user.GetAllUsers().ToList().Where(u => u.FirstName.Contains(Prefix) && u.usertypeid == stdid);
var StudentList = user.GetAllUsers().ToList();
var searchlist = (from student in StudentList1
where student.FirstName.Contains(Prefix)
select student).ToList();
return Json(StudentList1, JsonRequestBehavior.AllowGet);
}
// POST: Student/Create
[HttpPost]
public ActionResult Create(Models.StudentBatch student, IEnumerable<string> UserValues)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
If I understood correctly the problem here is passing multiple IDs from a listbox to a POST? One possible way is to assign viewbag like thus in your controller:
ViewBag.StudentList = new SelectList(db.StudentBatch, "studentId", "StudentName");
I use entities to access my models, I think you have a little bit different approach but the point is to give a collection to the Selectlist. Then you specify the data value field and the data text field.
Then in your view, note that it's not ListBoxFor, as it's dynamic:
#Html.ListBox("StudentList", null)
Then finally to be able to receive the values in the POST add the following parameter to your action and you should be able to iterate through it:
string[] StudentList
Finally managed to get the related from the listbox. I followed the instruction mentioned in a particular question. That's how i did.
$("#StudentName").autocomplete({
source: function (request, response) {
$.ajax({
cache: false,
// async: false, NEVER do this
url: '#Url.Action("CreateStudent", "Student")', // don't hard code your url's
data: { Prefix: request.term }, // change
dataType: "json",
type: "POST",
// contentType: "application/json; charset=utf-8", delete
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
id: item.id
}
}));
}
})
},select: function(event, ui) {
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("GetDetails", "Student")',
data: { id: ui.item.id },
success: function (data) {
var name = $("#StudentName").val();
$('#SelectedNames').
append($("<option></option>").
attr("value", ui.item.id).
text(name));
$('#hiddensq').append("<input name='UserValues' type='hidden' value='" + ui.item.id + "'/>");
}
});
}
});
</script>
and in the controller class
[HttpPost]
public JsonResult GetDetails(string id)
{
ViewBag.Value = id;
return Json(ViewBag.Value, JsonRequestBehavior.AllowGet);
}

How do I Show/Hide partial view based on result I get from service call using jQuery AJAX in MVC4?

I want to have a page where I can enter loan number then I will call a WCF get service to see if a loan number is valid. If loan# is valid, I want to show loan related data (partial view) on the same page.
Here is my main View:
#model LoanStatus.Web.Models.Validate
#{
ViewBag.Title = "Validate";
}
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
}
<script type="text/javascript">
jQuery(function ($) {
$("#txtssn").mask("9999");
});
function validateRequest() {
var $form = $('form');
if ($form.valid()) {
$.support.cors = true;
var lnkey = $('#txtlnkey').val();
$.ajax({
type: "GET",
url: "http://localhost:54662/Service1/ValidateRequest/" + encodeURIComponent(lnkey),
contentType: "application/json; charset=utf-8",
dataType: "json", //jsonp?
success: function (response) {
$('#Result').html('Loading....');
if (response.ValidateRequestResult.toString().toUpperCase() == 'TRUE') {
alert('validated');
} else {
alert('cannot validated' + response.ValidateRequestResult.toString().toUpperCase());
//$("#Result").hide();
}
$('#Result').html(response.ValidateRequestResult);
//alert(response.ValidateRequestResult.toString());
},
error: function (errormsg) {
alert("ERROR! \n" + JSON.stringify(errormsg));
}
});
//
} else {
$('#Result').html('Input Validation failed');
}
}
</script>
#using (Html.BeginForm()) {
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.LoanKey, new{})
#Html.TextBoxFor(m => m.LoanKey, new { #id = "txtlnkey" })
#Html.ValidationMessageFor(m => m.LoanKey)
</li>
</ol>
<input type="button" value="Get Status" onclick="javascript:validateRequest();" />
</fieldset>
}
<div id="Result">
#if (ViewBag.Validated)
{
#Html.Action("GetLoanInfo");
}
</div>
Below is my controller:
namespace LoanStatus.Web.Controllers
{
public class ValidateController : Controller
{
//
// GET: /Validate/
[HttpGet]
public ActionResult Index()
{
var model = new Validate() {LoanKey = "", Last4Ssn = ""};
ViewBag.Validated = false;
return View(model);
}
[HttpPost]
public ActionResult Index(Validate model, bool validated)
{
// do login stuff
ViewBag.Loankey = model.LoanKey;
ViewBag.Validated = true;
return View(model);
}
public ActionResult GetLoanInfo() // SHOWs Search REsult
{
return PartialView("_LoanInfoPartial", ViewBag.Loankey);
}
}
}
I want to have '#Html.Action("GetLoanInfo");' rendered only if jQuery AJAX service call returns TRUE (Where I have alert('validated'). I am not sure how to do that. My issue can be resolved if I can set value to ViewBag.Validated in success:function(). But based on what I read, it cannot be set in jQuery.
I tried $("#Result").hide(); and $("#Result").show(); but it did not work. Please help.
Can you try with this:
In your function validateRequest() ajax success, at the place where you are showing alert('validated'); use this and try:
$('#Result').load('#Url.Action("GetLoanInfo", "Validate")');
In your view make Result div empty
<div id="Result"> </div>
Tell me if it helps.

jquery ajax call from asp.net mvc app

I am trying to call an action from jQuery. The action should return true or false,
and based on the return value I will do something.
I have the following code.
$("#payment").click(function (e) {
if($("#deliverytime").attr("disabled")){
//something here...
}
else
{
var postcode=$('#Postcode').val();
var restId='<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid="+restId+"&&postcode="+postcode;
$.ajax({
type: "GET",
url: URL
}).done(function(msg) {
if(msg==true){
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
else{
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
});
}
});
The code is not working. It says 'msg' is not defined. Is this not the way I should do this using jQuery-ajax? What am I doing wrong?
EDIT:
Controller action
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(Boolean.FalseString, JsonRequestBehavior.AllowGet);
}
else
return Json(Boolean.TrueString, JsonRequestBehavior.AllowGet);
}
Modified function
var postcode = $('#DeliveryInfo_Postcode').val();
var restId = '<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid=" + restId + "&&postcode=" + postcode;
$.ajax({
url: URL,
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
$('#commonMessage').html(data);
return false;
}
}
});
EDIT -2
<script>
$(document).ready(function () {
$("#checkout").click(function (e) {
getDeliveryInfo();
});
});
function getDeliveryInfo() {
var URL ="/Restaurant/DoesRestaurantDeliver/6/2259"
$.get(URL, function (data) {
alert(data.isValid);
});
}
</script>
<%using (Html.BeginForm())
{ %>
<input type="submit" name="submit" id="checkout"/>
<%} %>
The above code does not work. But If i put the 'checkout' button out side of the form like below, it works.
<%using (Html.BeginForm())
{ %>
<%} %>
<input type="submit" name="submit" id="checkout"/>
You can configure your ajax call like below.
I feel your ajax call having problems on .done(function(msg) {} area.
Try to set success: function (data) {} like below.
<script type="text/javascript">
$(function () {
var companyName = $("#companyname");
$.ajax({
url: "/Company/GetName",
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
companyName.html(data.companyName);
}
}
});
});
</script>
EDIT
Action method should looks like below (This is a sample.Adjust it according to your situation)
[HttpGet]
public JsonResult GetName(string term)
{
var result = Repository.GetName(term);
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT 2
I would use Anonymous object (isValid) (remember that JSON is a key/value pairs):
Action Method
[HttpGet]
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(new { isValid = false},JsonRequestBehavior.AllowGet);
}
else
return Json(new { isValid = true },JsonRequestBehavior.AllowGet);
}
And then inside the ajax method:
success: function(data) {
if (data.isValid) {
...
}
}
EDIT 3
Just change your button type as below.(since you're not sending any values from form)
<input type="button" name="submit" id="checkout"/>

Resources