user2706372
user2706372

Reputation: 95

I can not return to PartialView by using JSON

I have been looking for return partialview by using json.However I can only see partial view's name as html.

İf Username and Password is not null , ı want to redirect to PartialView.

[HttpGet]
public ActionResult Index()
{
return View();
}

Index View:

<script type="text/javascript">
function test() {

var veri = {
KullaniciAd: $('#KullaniciAd').val(),
Sifre: $('#Sifre').val(),
};

$.ajax({
url: "/Home/Menu",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {

$("#message").html(mydata);
},
error: function () {
$("#message").html("error");
}
});

return false;

}
</script>

<input type="text" id="KullaniciAd" name="KullaniciAd" />
<input type="password" id="Sifre" name="Sifre" />
<input type="button" onclick="test()" value="Giriş" />


<div id="message"></div>

My Menu ActionResult

 public ActionResult Menu(MyModel model)
    {
        if (model.KullaniciAd != null && model.Sifre != null)
        {
            return Json("_MenuPartial", JsonRequestBehavior.AllowGet);

        }
        return null;
    }

Upvotes: 0

Views: 1877

Answers (2)

vborutenko
vborutenko

Reputation: 4443

You need render view to string

  public string RenderRazorViewToString(string viewName, object model)
  {
    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
      var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
      var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
      viewResult.View.Render(viewContext, sw);
      viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
      return sw.GetStringBuilder().ToString();
     }
  }

In controller

var stringView = RenderRazorViewToString("_MenuPartial",model)
return Json(stringView , JsonRequestBehavior.AllowGet);

Upvotes: 1

Paritosh
Paritosh

Reputation: 11560

That it because you are just returning _MenuPartial - string as Json data.

If you want to return JSON, then return JsonResult instead of ActionResult.
The below code should also work - ultimately, the browser will get HTML string as ajax call result from server

public ActionResult Menu(MyModel model)
{
    if (model.KullaniciAd != null && model.Sifre != null)
    {
        return View("_MenuPartial");

    }
    return null;
}

Upvotes: 0

Related Questions